Namespaced mapping object

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

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

      

for a dive object like this (output):

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

      

Of course, the solution must be prepared for an infinite deep level.

My solution doesn't 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 better conversion algorithm like mine?

+3


source to share


2 answers


You can use a function to split the value path and create new objects for it.



function setValue(object, path, value) {
    var way = path.split('-'),
        last = way.pop();

    way.reduce(function (o, k) {
        return o[k] = o[k] || {};
    }, object)[last] = value;
}

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

Object.keys(object).forEach(function (key) {
    if (key.indexOf('-') !== -1) {
        setValue(object, key, object[key]);
        delete object[key];
    }
});

console.log(object);
      

.as-console-wrapper { max-height: 100% !important; top: 0; }
      

Run code


+3


source




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);
      

Run code


0


source







All Articles