简体   繁体   中英

Javascript object destructuring/manipulation

Let's say I have the following object:

const original = {
  first: 1,
  second: 2,
  third: 3
}

and I want to create a new, distinct object with the following structure:

const modified = {
  first: 100,
  third: 3
}

ES6 syntax allows me to do some pretty powerful manipulation, like:

const {second, ...newElement} = original

which results in:

const newElement = {
  first: 1,
  third: 3
}

but then I would still have to do newElement.first = 100 .

Alternatively, I could do:

const newElement2 = Object.assign({}, original , {second: undefined, first: 100})

but this doesn't really delete second , it just sets it to undefined .


Is there a more elegant alternative to go from original to modified ?

Create an object with updated first: 100 using object spread , then destructure it using object rest .

Note: Object rest/spread is a Stage 4 proposal for ECMAScript, and not part of ES6.

 const original = { first: 1, second: 2, third: 3 } const { second, ...newElement } = { ...original, first: 100 }; console.log(newElement); 

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