Nest JSON from array

I am trying to achieve something that seemed very simple, but in recent days you make me angry.

I have a simple array: ["a","b","c","d","e"]and I want to turn it into nested JSON as follows:

{"a":{"b":{"c":{"d":{"e":""}}}}}

Going through it, I ran into problems such as "how to save the last key, to install it after that, without deleting it," etc.

Does anyone have any ideas?

+4
source share
3 answers

You may have had problems because you were stuck in the wrong direction. Try to build an object from the inside out:

array.reduceRight(function(v, key) {
    var o = {};
    o[key] = v;
    return o;
}, "")

or, with a loop:

var val = "";
for (var i=array.length; i--; )
    var o = {};
    o[array[i]] = val;
    val = o;
}
return val;
+4
source

Here is one way to do this, recursively:

function convertToNestedObject(arr) {
    var result = {};

    if (arr.length === 1) {
        result[arr[0]] = '';
    } else {
        result[arr[0]] = convertToNestedObject(arr.slice(1, arr.length));
    }

    return result;
}

slice :

function convertToNestedObject(arr, startIndex) {
    var result = {};


    if (arr.length - startIndex === 1) {
        result[arr[startIndex]] = '';
    } else {
        result[arr[startIndex]] = convertToNestedObject(arr, startIndex + 1);
    }

    return result;
}

: http://jsfiddle.net/jwcxfaeb/1/

+1

Put the current item as a key and an empty object ( {}) as a value. Continue to enter an empty object.

function toNested(arr){
    var nested = {};
    var temp = nested;

    for(var i=0; i<arr.length; i++){
        temp[arr[i]] = {};
        temp = temp[arr[i]];
    }

    return nested;
}
0
source

All Articles