简体   繁体   中英

How to remove object properties from nested arrays of objects?

I am trying to remove these 2 properties from each object in the array while it's not working. Each object is inside an array. I mean The main array contains arrays of objects. Is there an easy way to solve it without using the map() twice? And how to return the main modified array in that case?

const modifiedItems = this.items.map(item => {
   delete item.created,
   delete item.removed
   return item
})

Data looks like this:

this.items = [
  [{ removed: 1, created: 1, a:2, b: 2, c: 3}]
  [{ removed: 1, created: 1, a:2, b: 2, c: 3}, { removed: 1, created: 1, a:2, b: 2, c: 3},]
];

The above code doesn't work because it doesn't map to arrays inside the main array. How is the best to delete those properties from each object of all arrays located in the main array?

Instead of deleting, why not just return an object without the properties you want to remove.

You could destructure the properties you want to remove and then collect other properties in a variable using the rest parameters syntax. After this, you just need to return the variable which contains all the properties other than the ones you want to remove.

const modifiedItems = this.items.map(
   ({ created, removed, ...rest }) => rest
);

Following code snippet shows an example:

 const arr = [ { removed: 1, created: 1, a:2, b: 2, c: 3}, { removed: 1, created: 1, a:2, b: 2, c: 3}, { removed: 1, created: 1, a:2, b: 2, c: 3}, ]; const modifiedItems = arr.map( ({ created, removed, ...rest }) => rest ); console.log(modifiedItems);

Edit:

In your case, this.items is an array that contains nested arrays. So to remove the properties from the objects inside the nested arrays, you need to map over each nested array as well.

Following code snippet shows an example:

 const items = [ [ { removed: 1, created: 1, a: 2, b: 2, c: 3 } ], [ { removed: 1, created: 1, a: 2, b: 2, c: 3 }, { removed: 1, created: 1, a: 2, b: 2, c: 3} ] ]; const modifiedItems = items.map(subArr => { return subArr.map(({ created, removed, ...rest }) => rest) }); console.log(modifiedItems);

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