All files / platform/core/src object.js

3.33% Statements 1/30
0% Branches 0/10
0% Functions 0/3
3.33% Lines 1/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60                                                                                                          34x            
// Transforms a shallow object with keys separated by "." into a nested object
function getNestedObject(shallowObject) {
  const nestedObject = {};
  for (let key in shallowObject) {
    Iif (!shallowObject.hasOwnProperty(key)) {
      continue;
    }
    const value = shallowObject[key];
    const propertyArray = key.split('.');
    let currentObject = nestedObject;
    while (propertyArray.length) {
      const currentProperty = propertyArray.shift();
      if (!propertyArray.length) {
        currentObject[currentProperty] = value;
      } else {
        Iif (!currentObject[currentProperty]) {
          currentObject[currentProperty] = {};
        }
 
        currentObject = currentObject[currentProperty];
      }
    }
  }
 
  return nestedObject;
}
 
// Transforms a nested object into a shallowObject merging its keys with "." character
function getShallowObject(nestedObject) {
  const shallowObject = {};
  const putValues = (baseKey, nestedObject, resultObject) => {
    for (let key in nestedObject) {
      Iif (!nestedObject.hasOwnProperty(key)) {
        continue;
      }
      let currentKey = baseKey ? `${baseKey}.${key}` : key;
      const currentValue = nestedObject[key];
      if (typeof currentValue === 'object') {
        Iif (currentValue instanceof Array) {
          currentKey += '[]';
        }
 
        putValues(currentKey, currentValue, resultObject);
      } else {
        resultObject[currentKey] = currentValue;
      }
    }
  };
 
  putValues('', nestedObject, shallowObject);
  return shallowObject;
}
 
const object = {
  getNestedObject,
  getShallowObject,
};
 
export default object;