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
asked Aug 29, 2018 at 12:10
gugateider
2,0872 gold badges15 silver badges18 bronze badges
-
1Do you need to create just exactly this empty object? Or do you need to merge those keys into an existing objects also containing other keys?deceze– deceze ♦2018年08月29日 12:12:20 +00:00Commented Aug 29, 2018 at 12:12
-
It can be anything in the value for now as I got access to the data I need to add to this object, but it needs to be within this structure. Tksgugateider– gugateider2018年08月29日 12:13:37 +00:00Commented Aug 29, 2018 at 12:13
4 Answers 4
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);
answered Aug 29, 2018 at 12:15
Sign up to request clarification or add additional context in comments.
4 Comments
Cody Geisler
{[key]: res} --- has this always been a thing? [key]:value ?deceze
Not always. Computed keys exist since ES2016 or so.
Charles Wood
Bear in mind that
keys.reverse will mutate the original array. Using keys.reduceRight (as suggested below) may be preferable.devaent
If you want the final "leaf" of your object tree to contain a value other than an empty object, you can use a ternary
keys.reduceRight((res, key, i) => (i === keys.length - 1 ? {[key]: myValue} : {[key]: res}) , {});You can also do it with Array.prototype.reduceRight:
const result = ['product','model','version'].reduceRight((all, item) => ({[item]: all}), {});
console.log(result);
answered Aug 29, 2018 at 16:16
Leonid Pyrlia
1,7322 gold badges12 silver badges16 bronze badges
Comments
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']));
1 Comment
gugateider
Worked as expected !! Thanks for your help!!
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));
answered Apr 28, 2024 at 13:21
Bidisha Das
4026 silver badges15 bronze badges
Comments
Explore related questions
See similar questions with these tags.
lang-js