Spider Spider - 23 days ago 7
JSON Question

How to make a nested object using a string with dots

I have a mapping object which looks like below :

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


What i want is an object like following:

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


How can i achieve this?

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