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
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);
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']));
You can also do it with Array.prototype.reduceRight
:
const result = ['product','model','version'].reduceRight((all, item) => ({[item]: all}), {}); console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.