I have an array formatted like so
const array = [
['technology', 'apple', 'computers', 'macbook_pro'],
['technology', 'apple', 'computers', 'macbook_air'],
['technology', 'apple', 'phones', 'iphone'],
['technology', 'samsung', 'phones', 'Galaxy S21'],
]
And I need to convert it to an object formatted like so:
{
technology: {
apple: {
computers: {
macbook_pro: {},
macbook_air: {}
},
phones: {
iphone: {}
}
},
samsung: {
phones: {
galaxy_s21: {}
}
}
}
}
I tried getting it done with a two forEach loops but I keep getting stuck.
Using Array#reduce, iterate over the array while updating an object accumulator.
In every iteration, set a current to the accumulator and iterate over the current list using Array#forEach. If current doesn't have a property, set the value to {} using the nullish operator. Then, reset current to it to be used in the next iteration.
const array = [
['technology', 'apple', 'computers', 'macbook_pro'],
['technology', 'apple', 'computers', 'macbook_air'],
['technology', 'apple', 'phones', 'iphone'],
['technology', 'samsung', 'phones', 'Galaxy S21'],
];
const res = array.reduce((acc, props) => {
let current = acc;
props.forEach(prop => {
current[prop] ??= {};
current = current[prop];
});
return acc;
}, {});
console.log(res);
Array.reduce implementation is added below
arrayconst array = [
['technology', 'apple', 'computers', 'macbook_pro'],
['technology', 'apple', 'computers', 'macbook_air'],
['technology', 'apple', 'phones', 'iphone'],
['technology', 'samsung', 'phones', 'Galaxy S21'],
]
const output = array.reduce((acc, curr) => {
let temp = acc;
curr.forEach((node) => {
if (!temp[node]) {
temp[node] = {}
}
temp = temp[node]
})
return acc;
}, {});
console.log(output)