given an array like [‘a’, ‘b’, ‘c’]
how can i get an object like
{
current: ‘a’,
next : {
current: ‘b’,
next: {
current: ‘c’
}
}
}
asked Aug 6, 2021 at 19:20
RenaissanceProgrammer
4941 gold badge12 silver badges30 bronze badges
2 Answers 2
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.
answered Aug 6, 2021 at 19:27
Kelvin Schoofs
8,7462 gold badges17 silver badges34 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
RenaissanceProgrammer
i ended up using this answer as it also translates to other languages easily
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)
answered Aug 6, 2021 at 19:28
Ori Drori
196k32 gold badges243 silver badges233 bronze badges
2 Comments
RenaissanceProgrammer
both answers are good, i’m not sure which to select
Ori Drori
lol. Try them both for your use case, and see which is more readable, and works better for you.
lang-js