given an array like [‘a’, ‘b’, ‘c’]
how can i get an object like
{
current: ‘a’,
next : {
current: ‘b’,
next: {
current: ‘c’
}
}
}
You can make a recursive function for this:
const data = ['a', 'b', 'c'];
function createObj([current, ...rest]) {
const result = { current };
if (rest.length) result.next = createObj(rest);
return result;
}
console.log(createObj(data));
The [current, ...rest]
is a single destructured array argument.
You can use Array.reduceRight()
to create the object:
const arr = ['a', 'b', 'c']
const obj = arr.reduceRight((acc, o) => ({
current: o,
...acc && { next: acc }
}), null)
console.log(obj)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With