Harry
Harry

Reputation: 328

Nest JSON from array

I am trying to achieve something which seemed very basic but is getting me mad over the last days.

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

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

Looping over it, I ran in problems like "how do you save the last key to set it afterwards without erasing it" and so on.

Does anyone has an idea?

Upvotes: 4

Views: 662

Answers (3)

Andrew Whitaker
Andrew Whitaker

Reputation: 126082

Here's one way to do it, 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;
}

You could pass the start index in to the function instead of using slice and creating copies of the array:

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


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

    return result;
}

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

Upvotes: 1

Cem Özer
Cem Özer

Reputation: 1283

Put current element as key and empty object ({}) as value. Continue with newly inserted 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;
}

Upvotes: 0

Bergi
Bergi

Reputation: 665574

You might have had problems because you were looping in the wrong direction. Try to build the object from 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;

Upvotes: 4

Related Questions