Remove objects(items) from array json those are not listed in another array using Typescript

Viewed 77

I would like to remove objects from array JSON those are not listed in another array.

let originalArray = [{
  id: 1,
  NoOfEmp: 12,
  Wages:1000,
  TotalSI: 21,
  Salary:3000
}, {
   id: 2,
  NoOfEmp: 13,
  Wages:2000,
  TotalSI: 22,
  Salary:4000
}]

let keepArrayObjects = ['id','NoOfEmp','Wages']


originalArray = originalArray.filter( function( el ) {
  return keepArrayObjects.indexOf( el ) >  0;
} );

console.log(originalArray); 

I have tried the above code to remove objects "TotalSI", "Salary" and keep objects that are listed in keepArrayObjects array, but it's not working.

I would like to update the original array itself and Please help me with this.

2 Answers

You could map wanted entries and get new objects.

let array = [{ id: 1, NoOfEmp: 12, Wages: 1000, TotalSI: 21, Salary: 3000 }, { id: 2, NoOfEmp: 13, Wages: 2000, TotalSI: 22,  Salary: 4000 }],
    keys = ['id', 'NoOfEmp', 'Wages'],
    result = array.map(o => Object.fromEntries(keys.map(k => [k, o[k]])));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

IE compatible version

var array = [{ id: 1, NoOfEmp: 12, Wages: 1000, TotalSI: 21, Salary: 3000 }, { id: 2, NoOfEmp: 13, Wages: 2000, TotalSI: 22,  Salary: 4000 }],
    keys = ['id', 'NoOfEmp', 'Wages'],
    result = array.map(function (source) {
        return keys.reduce(function (target, k) {
            target[k] = source[k];
            return target;
        }, {});
    });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

If you want to remove properties from an object:

originalArray.filter((el) => {
  for (let prop in el) {
    if (!keepArrayObjects.includes(prop)) {
      delete el[prop]
    }
  }
});

console.log(originalArray);
Related