Spider Spider - 23 days ago 8
JSON Question

How to form a nested javascript object using a string with dots as property hierarchy

I have a mapping object in which property and Value looks like below :

var obj = {
key: "key1.key2.key3.key4"
};


How to convert
obj
to nested javascript object as shown below:

var returnObj = {
key1: {
key2: {
key3:{
key4: {
"value": key
}
}
}
}
};

Answer Source

You could iterate the keys and then split the string for single properties. Then create objects, if not exists. Later assign the original key as value.

function convert(object) {
    var result = {};
    Object.keys(object).forEach(function (k) {
        object[k].split('.').reduce(function (o, k) {
            return o[k] = o[k] || {};
        }, result).value = k;
    });
    return result;
}

var obj = { key: "key1.key2.key3.key4" };

console.log(convert(obj));
  
.as-console-wrapper { max-height: 100% !important; top: 0; }