Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove property key using filter()

Tags:

javascript

var a = [{'id':1,'name':'James','age':11}];

a = a.filter(function( obj,i ) {
            //return obj != 'age';
          });

filter will create a new array, but how to splice away the age property key? Didn't use jquery, can't use $.grep in this case. and won't use delete because it's not really delete the key but leave an empty slot.

like image 215
Jamie Jordan Avatar asked Jun 28 '26 11:06

Jamie Jordan


1 Answers

Use Array#forEach and delete operator to delete the key

var a = [{
  'id': 1,
  'name': 'James',
  'age': 11
}, {
  'id': 2,
  'name': 'James2'
}];

a.forEach(function(obj, i) {
  obj['age'] && delete obj['age'];
});
console.log(a);
like image 197
Rayon Avatar answered Jul 01 '26 02:07

Rayon



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!