2

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

2 Answers 2

2

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

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

5 Comments

Thank you very much. But "fromEntries" will work for IE ? caniuse.com/?search=fromEntries
no, it does not. you need to reduce with an object.
Can you please give me a solution which will work for IE also ?
How can I remove items directly in originalArray where id =2 only ? the desired result would be [{ id: 1, NoOfEmp: 12, Wages: 1000, TotalSI: 21, Salary: 3000 }, { id: 2, NoOfEmp: 13, Wages: 2000 }]. I have tried with originalArray .filter(l=>l.id == 2).map... but originalArray is not changing..
you need to address the object at the wanted index for changing: array.map((o, i) => i === 2 ? Object.fromEntries(keys.map(k => [k, o[k]])) : o)
1

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

Comments

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.