Conversion object by namespace

Viewed 87

I need to convert "flat object" like this (input data):

{
   'prop1': 'value.1',
   'prop2-subprop1': 'value.2.1',
   'prop2-subprop2': 'value.2.2',
}

to immersion object like this (output data):

{
   'prop1': 'value.1',
   'prop2': {
      'subprop1': 'value.2.1',
      'subprop2': 'value.2.2'
   }
}

Of course solution have to be prepare for no-limit deep level.

My solution does not work:

var inputData = {
   'prop1': 'value.1',
   'prop2-subprop1': 'value.2.1',
   'prop2-subprop2': 'value.2.2',
};    

function getImmersionObj(input, value) {
   var output = {};

   if ($.type(input) === 'object') { // first start
      $.each(input, function (prop, val) {
         output = getImmersionObj(prop.split('-'), val);
      });
   } else if ($.type(input) === 'array') { // recursion start
      $.each(input, function (idx, prop) {
         output[prop] = output[prop] || {};
         output = output[prop];
      });
   }

   return output;
}

console.log(getImmersionObj(inputData)); // return empty object

Can you help me find the problem in my code or maybe you know another one, better algorithm for conversion like my?

2 Answers

var input = {
    "property1": "value1",
    "property2.property3": "value2",
    "property2.property7": "value4",
    "property4.property5.property6.property8": "value3"
}

function addProp(obj, path, pathValue) {
    var pathArray = path.split('.');
    pathArray.reduce(function (acc, value, index) {
        if (index === pathArray.length - 1) {
            acc[value] = pathValue;
            return acc;
        } else if (acc[value]) {
            if (typeof acc[value] === "object" && index !== pathArray.length - 1) {
                return acc[value];
            } else {
                var child = {};
                acc[value] = child;
                return child;
            }
        } else {
            var child = {};
            acc[value] = child;
            return child;
        }
    }, obj);
}

var keys = Object.keys(input);
var output = {};
keys.forEach(function (k) {
    addProp(output, k, input[k]);
});
console.log(output);

Related