[英]Delete multiple keys from array of Object
Let's say we have an array of object:假设我们有一个 object 数组:
var obj = [{a: 1, b: 2, c: 3, d: 4, e: 5 },{a: 6, b: 7, c:
8, d: 9, e: 0 }];
and we want to delete key c,e from both of the objects.我们想从两个对象中删除键 c,e 。
How can it be done?怎么做到呢? One of the methods I found is:我发现的一种方法是:
['c', 'e'].forEach(e => delete obj[e]); //for object
Is there any other way so we don't have to use double for loop.有没有其他方法,所以我们不必使用双循环。
One way to do it is to use .map()
together with object destructuring :一种方法是将.map()
与object 解构一起使用:
var obj = [ { a: 1, b: 2, c: 3, d: 4, e: 5 }, { a: 6, b: 7, c: 8, d: 9, e: 0 }, ]; var newObj = obj.map(({ c, e, ...rest }) => rest); console.log(newObj)
This will create a new array with new objects which contain all of the other keys except for c
and e
.这将创建一个包含新对象的新数组,其中包含除c
和e
之外的所有其他键。
You have 2 options to resolve it:您有 2 个选项来解决它:
map(({ a,b,c,d,e }) => ({a,b,d})
通过使用object 解构: map(({ a,b,c,d,e }) => ({a,b,d})
{ c, e, ...rest }
使用 [Rest parameters] { c, e, ...rest }
增强选项 1 Object destructuring
like below Object destructuring
如下
const obj = { a: 1, b: 2, c: 3, d: 4, e: 5 } var {c, e} = obj; // c = 3, e = 5
With option 2, you will have c,e
implicit name and the remaining items
named rest
.使用选项 2,您将拥有c,e
隐式名称和名为rest
the remaining items
。 After that, you just need to get rest
items.之后,您只需要获得rest
项目。
Option 1选项1
var obj = [ { a: 1, b: 2, c: 3, d: 4, e: 5 }, { a: 6, b: 7, c: 8, d: 9, e: 0 }, ]; console.log(obj.map(({ a,b,c,d,e }) => ({a,b,d})));
Option 2选项 2
var obj = [ { a: 1, b: 2, c: 3, d: 4, e: 5 }, { a: 6, b: 7, c: 8, d: 9, e: 0 }, ]; console.log(obj.map(({ c, e, ...rest }) => rest)); //...rest: the same as `a,b,d`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.