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
toString() method is used to convert: an array of numbers, strings, mixed arrays, arrays of objects, and nested arrays into strings.
To convert an object to an array you use one of three methods: Object. keys() , Object. values() , and Object. entries() .
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']));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With