gugateider
gugateider

Reputation: 2039

Convert array into nested object

Let's say I have the following array: ['product' , 'model', 'version']

And I would like to have an object such as:

{
    product: { 
        model: { 
            version: { 

            }
        }
     }
}

However, that array is dynamic so it could have 2, 3 or fewer more items. How can this be achieved in the most efficient way?

Thanks

Upvotes: 7

Views: 7699

Answers (4)

Bidisha Das
Bidisha Das

Reputation: 402

function convert(namesArray, val) {
  let result = {};
  let nestedObj = result;
  namesArray.forEach((name, index) => {
    nestedObj[name] = index === namesArray.length - 1 ? val : {};
    
    nestedObj = nestedObj[name];
  });

  return result;
}
console.log(convert(["a", "b", "c"], 3));

Upvotes: 0

Leonid Pyrlia
Leonid Pyrlia

Reputation: 1702

You can also do it with Array.prototype.reduceRight:

const result = ['product','model','version'].reduceRight((all, item) => ({[item]: all}), {});

console.log(result);

Upvotes: 9

deceze
deceze

Reputation: 522016

Just turn it inside out and successively wrap an inner object into an outer object:

const keys = ['product', 'model', 'version'];
const result = keys.reverse().reduce((res, key) => ({[key]: res}), {});
//                                   innermost value to start with ^^

console.log(result);

Upvotes: 16

Andrey
Andrey

Reputation: 4050

If I understood request correctly, this code might do what you need:

function convert(namesArray) {
  let result = {};
  let nestedObj = result;
  namesArray.forEach(name => {
    nestedObj[name] = {};
    nestedObj = nestedObj[name];
  });

  return result;
}


console.log(convert(['a', 'b', 'c']));

Upvotes: 2

Related Questions