Convert array into nested object

Viewed 4470

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

3 Answers

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);

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

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

console.log(result);

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']));
Related