Roberto Lonardi Roberto Lonardi - 10 months ago 47
JSON Question

Create Javascript object from Keys arrays

I'm struggling with an operation I can't achieve, I have a number of arrays like these:

['key1', 'key2', 'key3']
['key1', 'key2', 'key4']
['key1', 'key5']

For each of this array there is a corresponding value:


I want to create an empty object from each array, that has an hierarchy based on the keys position in the array, for example:

['key1', 'key2', 'key3'] => { key1: { key2: { key3: value1 } } }

And at the end, merge these objects and build an object that is as this:

var object = {
key1: {
key2: {
key3: value1,
key4: value2
key5: value3

I tried some approaches but they require three for loops iterations and I think there is a better way for doing this, of course the merge at the end is the easiest part, I can just user the jQuery merge to do so, but I'm really struggling on create the single object from each array.

Thank you very much, if you need any more information let me know.


Answer Source

You could use Array#reduce, because this returns the object you need, without keeping a reference outside.

function set(object, path, value) {
    var last = path.pop();

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

var a = {};

set(a, ['key1', 'key2', 'key3'], 'value1'); 
set(a, ['key1', 'key2', 'key4'], 'value2'); 
set(a, ['key1', 'key5'], 'value3');