-1

I have an array in java script .. something like: var myarray = ['a','b',c']; and var item = 'Name'; and I want to convert that to something like

{
 a:{
    b:{
       c:{
          item:'Name'     
         }
      }
   }
}
2
  • 3
    That's an object, not JSON. Commented Jul 3, 2014 at 9:38
  • @Barmar is right. But in case you do need a JSON string and simply didn't format the question correctly, just take one of the answers below, and do JSON.stringify( result ) to get a JSON representation of that object Commented Jul 3, 2014 at 9:48

2 Answers 2

3
var result = myarray.reverse().reduce(function (value, key) {
    var result = {};
    result[key] = value;
    return result;
}, { item : item });

In other words, you're packing the result layer by layer into new objects, using your keys from the array.

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

1 Comment

That probably should be reverse().reduce( ... )
1
var obj = {};
var curobj = obj;
for (var i = 0; i < myarray.length; i++) {
    var newObj = {};
    newObj[myarray[i]] = newObj;
    curObj = newObj;
}
curObj.item = item;

The result you want will be in the obj object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.