Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 654
gugateider Avatar asked Aug 29 '18 12:08

gugateider


People also ask

Which method is used to convert nested arrays to objects?

toString() method is used to convert: an array of numbers, strings, mixed arrays, arrays of objects, and nested arrays into strings.

Can you convert an object to an array?

To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .


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);
like image 162
deceze Avatar answered Sep 30 '22 11:09

deceze


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

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

console.log(result);
like image 32
Leonid Pyrlia Avatar answered Sep 30 '22 11:09

Leonid Pyrlia


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']));
like image 43
Andrey Avatar answered Sep 30 '22 10:09

Andrey