简体   繁体   English

如何删除数组中每个对象的属性?

[英]How to remove a property for each object in an array?

Let say I have 假设我有

let a = [{
  foo: 1
  bar: 1
  baz: 1
},{
  foo: 2
  bar: 2
  baz: 2
},{
  foo: 3
  bar: 3,
  baz: 3
}];

How can I remove bar in every object so I get 如何删除每个对象中的bar ,以便获得

a = [{ foo: 1, baz: 1 }, { foo: 2, baz: 2 }, { foo: 3, baz: 3 }];

I simplified the example but each object can have many properties. 我简化了示例,但是每个对象可以具有许多属性。

Use .map to transform each element of an array into another. 使用.map将数组的每个元素转换为另一个。 Also note that your snippet's syntax is invalid; 另请注意,您的代码段语法无效; properties of an object need to be separated with a comma. 对象的属性需要用逗号分隔。

 const input = [{ foo: 1, bar: 1 },{ foo: 2, bar: 2 },{ foo: 3, bar: 3 }]; const output = input.map(({ foo }) => ({ foo })); console.log(output); 

If you want to remove one property rather than save some particular properties, you can do something similar using object rest/spread: 如果要删除一个属性而不是保存某些特定属性,则可以使用对象剩余/扩展执行类似的操作:

 const input = [{ foo: 1, bar: 1, baz: 1 },{ foo: 2, bar: 2, baz: 2 },{ foo: 3, bar: 3, baz: 3 }]; const output = input.map(({ foo, ...otherProps }) => ({ ...otherProps })); console.log(output); 

use Object.assign so you don't loose the first object and create a new one with the desired properties : 使用Object.assign这样您就不会丢失第一个对象并创建具有所需属性的新对象:

 const a = [{ foo: 1, bar: 1, baz: 1 },{ foo: 2, bar: 2, baz: 2 },{ foo: 3, bar: 3, baz: 3 }]; const b = Object.assign(a.map(({foo, baz}) => ({foo, baz}) ), {}); console.log( JSON.stringify(b) ) console.log(a) 

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

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