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)