简体   繁体   中英

Angular 9 How to drop a field from all arrays of an object of arrays in angular?

Lets say I am having the following list which is called indexesToBeRemoved :

indexesTobeRemoved = ['auto_id', 'auto_date']

I want to loop over the following array of arrays:

allArrays = [
    {
      'auto_id': 123,
      'auto_date': '2019-02-02',
      'name': 'John Doe',
      'address': 'USA'
    },
    {
      'auto_id': 147,
      'auto_date': '2019-03-02',
      'name': 'Peter Doe',
      'address': 'USA'
    },
    {
      'auto_id': 258,
      'auto_date': '2019-04-02',
      'name': 'Hanna Doe',
      'address': 'USA'
    }
  ];

I need to loop over each array within this array to remove fields that exists in the list indexesTobeRemoved . Therefore, the array of arrays would look like the following:

allArrays = [
    {
      'name': 'John Doe',
      'address': 'USA'
    },
    {
      'name': 'Peter Doe',
      'address': 'USA'
    },
    {
      'name': 'Hanna Doe',
      'address': 'USA'
    }
  ];

I tried the following:

removeIndexes() {
    this.indexesTobeRemoved.forEach((value) => {
      console.log(value);
      Object.keys(this.allArrays).forEach((key, val) => {
        this.allArrays.splice(value, 1);
        console.log(this.allArrays[key]);
      });
    })

But on execution, the array allArray will become empty.

Here is a stackblitz .

You can use nested forEach() loop and delete operator

 const allArrays = [ { 'auto_id': 123, 'auto_date': '2019-02-02', 'name': 'John Doe', 'address': 'USA' }, { 'auto_id': 147, 'auto_date': '2019-03-02', 'name': 'Peter Doe', 'address': 'USA' }, { 'auto_id': 258, 'auto_date': '2019-04-02', 'name': 'Hanna Doe', 'address': 'USA' } ]; let keys = ['auto_id', 'auto_date']; allArrays.forEach(x => { keys.forEach(k => delete x[k]) }) console.log(allArrays)

Instead of forEach please use map . Here's an explanation why:

https://gofore.com/en/why-you-should-replace-foreach/

What you were searching for was the delete operator. The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.

this.indexesTobeRemoved.map(key => {  
  this.allArrays.map(array => delete array[key]);
});

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