Skip to content Skip to sidebar Skip to footer

Conversion Object By Namespace

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 thi

Solution 1:

You could use a function for spliting the path to the value and generate new objects for it.

functionsetValue(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; }

Solution 2:

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

functionaddProp(obj, path, pathValue) {
    var pathArray = path.split('.');
    pathArray.reduce(function (acc, value, index) {
        if (index === pathArray.length - 1) {
            acc[value] = pathValue;
            return acc;
        } elseif (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);

Post a Comment for "Conversion Object By Namespace"