1

Basically i want to create a tree structure. For example if you have an array of four items ['a', 'b', 'c', 'd'] then i need a JSON from this which should be

{a: {b: {c: {d: 0} } } }

last item of JSON have value of 0 or it can be anything except object.

3
  • 4
    What did your try already? Commented Jul 2, 2015 at 13:46
  • "Recursion" comes to mind... Commented Jul 2, 2015 at 13:49
  • Do you want a JSON string or a Javascript Object? Commented Jul 2, 2015 at 16:18

2 Answers 2

6

The conversion steps are straightforward with simple loop:

  • Reverse the array, so the last becomes the first to convert (and it becomes the inner-most element of JSON).
  • Iterate through each element, make key-value pair of the object, wrap it repeatedly.
  • Done

Sample code:

var array = ['a', 'b', 'c', 'd']; // input array
var json = {}; // output object
array.reverse().forEach(function(el){
    if (Object.keys(json).length==0){
        json[el] = 0;
    }
    else{
        var outer = {};
        outer[el] = json;
        json = outer;
    }
});

Output

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

Sign up to request clarification or add additional context in comments.

1 Comment

Using reduceRight would have been a much simpler solution, if you are going to use ES5 methods.
2

In an ES5 environment.

var data = ['a', 'b', 'c', 'd'],
    jsObject = data.reduceRight(function (acc, datum) {
        var val = {};
            
        val[datum] = acc;
        
        return val;
    }, 0),
    jsonString = JSON.stringify(jsObject);

document.getElementById('out').textContent = jsonString;
<pre id="out"></pre>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.