5
\$\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.

\$\endgroup\$

3 Answers 3

4
\$\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);
\$\endgroup\$
1
  • \$\begingroup\$ Beautiful solution. Thank you so much for this. 🙏 \$\endgroup\$ Commented Dec 16, 2019 at 16:45
3
\$\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);

\$\endgroup\$
2
\$\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) ;

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.