2

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.

2 Answers 2

4

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)

Sign up to request clarification or add additional context in comments.

1 Comment

@alim1990 Accept the answer if you are satisfied with it.
2

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]);
});

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.