@forter/form-section
Version:
form-section from Forter Components
70 lines (64 loc) • 1.72 kB
JavaScript
export const set = (obj, path = '', value) => {
let schema = obj;
const pList = path.split('.');
const len = pList.length;
for (let i = 0; i < len - 1; i++) {
const elem = pList[i];
if ( !schema[elem] ) schema[elem] = {};
schema = schema[elem];
}
schema[pList[len - 1]] = value;
};
export const get = ( obj, keys = '', defaultVal ) => {
keys = Array.isArray( keys ) ? keys : keys.split('.');
obj = obj[keys[0]];
if ( obj && keys.length > 1 ) {
return get( obj, keys.slice(1) );
}
return obj === undefined ? defaultVal : obj;
};
export const unset = (obj = {}, path = '') => {
let currentObject = obj;
const parts = path.split('.');
const last = parts.pop();
for (const part of parts) {
currentObject = currentObject[part];
if (!currentObject) {
return;
}
}
delete currentObject[last];
};
export const isEmpty = value => {
const type = typeof value;
if ((value !== null && type === 'object') || type === 'function') {
const properties = Object.keys(value);
if (properties.length === 0 || properties.size === 0) {
return true;
}
}
if (value === 0) {
return false;
}
return !value;
};
export const clear = (obj, path = '') =>{
// Clear
unset(obj, path);
// Remove empty objects along the path
const parts = path.split('.');
for (let idx = parts.length; idx !== 0; idx--) {
const curPath = parts.slice(0, idx).join('.');
const currVal = get(obj, curPath);
if (currVal && isEmpty(currVal)) {
unset(obj, curPath);
}
}
};
export const removeItemFromArray = (array, item) => {
const index = array.indexOf(item);
if (index > -1) {
array.splice(index, 1);
}
return array;
};