简体   繁体   中英

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?

Could you use that

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

You can use merging here like:

 let eat = { when: 'now' } const fruits = ['apple', 'orange'] eat = {...eat, fruit: fruits[1]} console.log( eat )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM