Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript keep certain properties across objects in array

I want to remove every attribute from objects in array except for some of them:

var listToKeep = ['name', 'school'];

var arrayOfObjects = [{id:'abc',name:'oh', school: 'a', sport: 'a'},
                      {id:'efg',name:'em', school: 'b', sport: 's'},
                      {id:'hij',name:'ge', school: 'c', sport: 'n'}]

I am trying with this, but this is only trying to remove one:

arrayOfObjects .forEach(function(v){ delete v.id});

the expected result will be:

var arrayOfObjects = [{name:'oh', school: 'a'},
                          {name:'em', school: 'b'},
                          {name:'ge', school: 'c'}]

i don't want to use for loop.

like image 490
Bonnard Avatar asked Oct 26 '25 03:10

Bonnard


2 Answers

You can map each item in your array to new one, created by reducing list of keys to keep:

const newArray = arrayOfObjects.map(obj => listToKeep.reduce((newObj, key) => {
  newObj[key] = obj[key]
  return newObj
}, {}))

If you want to mutate original objects and delete properties, you can use two forEach loops and delete operator:

arrayOfObjects.forEach(obj => listToKeep.forEach((key) => {
  delete obj[key]
}, {}))

If you can use lodash or similar library, you can pick properties of object, e.g.:

const newArray = arrayOfObjects.map(obj => _.pick(obj, listToKeep))
like image 189
madox2 Avatar answered Oct 28 '25 15:10

madox2


You can loop over the keys of each JSON object in the arrayOfObjects array and then if the key is not found in the array listToKeep then remove that key:value from the object. And since you want to change the existing arrayOfObjects so you can follow this approach to use delete on the object property.

var listToKeep = ['name', 'school'];

var arrayOfObjects = [{id:'abc',name:'oh', school: 'a', sport: 'a'},
                      {id:'efg',name:'em', school: 'b', sport: 's'},
                      {id:'hij',name:'ge', school: 'c', sport:'n'}];
arrayOfObjects.forEach((obj)=>{
  Object.keys(obj).forEach((key)=>{
     if(listToKeep.indexOf(key) === -1){
       delete obj[key];
     }
  });
});
console.log(arrayOfObjects);
                      
like image 29
Ankit Agarwal Avatar answered Oct 28 '25 15:10

Ankit Agarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!