简体   繁体   English

Javascript对象的解构/操作

[英]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: ES6语法使我可以执行一些非常强大的操作,例如:

const {second, ...newElement} = original

which results in: 结果是:

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

but then I would still have to do newElement.first = 100 . 但是我仍然必须做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 . 但是这并没有真正删除second ,它只是将其设置为undefined


Is there a more elegant alternative to go from original to modified ? originalmodified还有其他更优雅的选择吗?

Create an object with updated first: 100 using object spread , then destructure it using object rest . 首先创建一个更新的对象first: 100使用对象传播 first: 100 ,然后使用对象rest对其进行解构。

Note: Object rest/spread is a Stage 4 proposal for ECMAScript, and not part of ES6. 注意: 对象剩余/扩展是ECMAScript的第4阶段建议,而不是ES6的一部分。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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