igorpavlov
igorpavlov

Reputation: 3626

How to use array destructuring and assign to an object property in JavaScript ES6

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?

Upvotes: 0

Views: 69

Answers (2)

palaѕн
palaѕн

Reputation: 73896

You can use merging here like:

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

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

Upvotes: 1

Ahmed Kesha
Ahmed Kesha

Reputation: 830

Could you use that

[, eat.fruit] = fruits // remove const
console.log(eat)

Upvotes: 2

Related Questions