1

I need to create an object from an array.

For example,

I have a array like var arr = ['a', 'b', 'c'];

it should be converted to,

{
  a:{
    b:{
      c:{
      
      }
    }
  }
}

I tried the below code but not able to create a deep tree,

var arr = ['a', 'b', 'c'];
var obj = {},
    temp = 'asd';
for(var i=0; i<arr.length; i++){
    if($.isEmptyObject(obj)){
        obj[arr[i]] = {};
    } else {
        console.log(Object.keys(obj));
        obj[Object.keys(obj)][arr[i]] = {};
    }
}
console.log(obj, temp);

Fiddle

Can someone help me?

Thanks in advance.

0

1 Answer 1

9

You can try something like

var arr = ['a', 'b', 'c'];
var obj = temp = {};
for (var i = 0; i < arr.length; i++) {
  temp = temp[arr[i]] = {}
}

$('#result').html(JSON.stringify(obj))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="result"></div>

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

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.