4

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

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

i ended up using this answer as it also translates to other languages easily
5

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

2 Comments

both answers are good, i’m not sure which to select
lol. Try them both for your use case, and see which is more readable, and works better for you.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.