6
\$\begingroup\$

var a = ["a", "b", "c", "d"]
var res = {}
var value = "Hello"
for(var i=a.length; i > 0; i-- ){
 var item = a[i-1]
 var temp = {}
 temp[item] = i == a.length ? value : {}
 if(i != a.length){
 Object.keys(res).forEach(r => {
 temp[item][r] = res[r]
 })
 }
 res = temp
}
console.log(res)

The result is :

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

Which is right, exactly what I need. I was just wondering if I'm doing it the right way or is there any better solutions for this?

Thanks in advance.

asked Jun 19, 2017 at 13:49
\$\endgroup\$

3 Answers 3

5
\$\begingroup\$

You are currently mixing declarative and functional style. I suggest succinct functional style:

var keys = ["a", "b", "c", "d"];
var value = "Hello";
var res = keys.reduceRight((value, key) => ({[key]: value}), value);
answered Jun 20, 2017 at 17:04
\$\endgroup\$
0
4
\$\begingroup\$

I think, iterating the array once in the reverse order will be easy to create the nested object from array.

Steps:

1. Iterate the array in reverse order.

2. If index is equal to the length of array then assign the value to that key.

3. For all other cases simply put the previous object inside the new key.

Check this:

var a = ["a", "b", "c", "d"];
var res = {};
var value = "Hello";
for(let i = a.length - 1; i >= 0 ; i--){
 if(i == a.length - 1)
 res = { [a[i]] : value}; // assign the value
 else
 res = { [a[i]] : res}; //put the prev object
}
console.log(res);

answered Jun 19, 2017 at 15:21
\$\endgroup\$
3
\$\begingroup\$
  • Declare your variables outside the loop (or use let inside the loop).
  • The checking i > 0 in the for loop is unnecessary as i-- will be falsy when it gets to zero anyway. This also allows you to use i as the array index instead of i-1
  • Add commas and semi-colons where appropriate.

var 
 a = ["a", "b", "c", "d"],
 res = {},
 value = "Hello",
 item, temp;
 
for(var i=a.length; i--; ){
 item = a[i], temp = {} ;
 temp[item] = i == a.length-1 ? value : {} ;
 if(i != a.length){
 Object.keys(res).forEach(r => {
 temp[item][r] = res[r] ;
 })
 }
 res = temp ;
}
console.log(res) ;

answered Jun 19, 2017 at 14:56
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.