0

This code:

const eat = { when: 'now' }
const fruits = ['apple', 'orange']

eat.fruit = fruits[1] // orange

I can use array destructuring like this:

const [, selectedFruit] = fruits

eat.fruit = selectedFruit

But can I make a one-liner out of it?

2 Answers 2

2

Could you use that

[, eat.fruit] = fruits // remove const
console.log(eat)
Sign up to request clarification or add additional context in comments.

Comments

1

You can use merging here like:

let eat = { when: 'now' }
const fruits = ['apple', 'orange']

eat = {...eat, fruit: fruits[1]}
console.log( eat )

1 Comment

Although works but I won't recommend this. Compromising efficiency just to get one liner solution is not good idea, at least IMHO. Instead, one can create a new property and assign it the selected value by finding in the same statement e.g eat.fruit = fruits.indexOf() or something similar.

Your Answer

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.