For example, a function that would be const arrToNestObj = arr => {}
and would get [a, b, c, d, e]
and return
a: {
b: {
c: {
d: {
e: {
}
}
}
}
}
Thanks!
CodePudding user response:
Use Array.reduceRight()
to create a nested object:
const arrToNestObj = arr =>
arr.reduceRight((acc, key) => ({ [key]: acc }), {})
const arr = ['a', 'b', 'c', 'd', 'e']
const result = arrToNestObj(arr)
console.log(result)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>