On a second thought, makeNestedObjWithArrayItemsAsKeys can further be simplified, and written concisely!
const makeNestedObjWithArrayItemsAsKeys = (arr) => {
const reducer = (acc, item) => ({ [item]: acc });
return arr.reduceRight(reducer, {});
};
cc: dvv.avinash Ivan Rahul Sidhant Siddarthan
The Object.assign in the original function (below) is unnecessary... have noticed it thanks to Jason's answer!
It'd be amiss on my part, to not mention that Jason's solution here (as I see it) is the most elegant one of the lot!
const makeNestedObjWithArrayItemsAsKeys = (arr) => {
return arr.reduceRight(
(accumulator, item) => {
const newAccumulator = {};
newAccumulator[item] = Object.assign(
{},
accumulator
);
return newAccumulator;
},
{}
);
};
Given the following list:
const list = ["a", "b", "c"];
...the return value of makeNestedObjWithArrayItemsAsKeys(list) will be the following object:
{
a: {
b: {
c: {}
}
}
}
Hope that answers your question! :)