3
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.

Jamie Jordan
  • 241
  • 1
  • 4
  • 16
  • Use `.map` instead.. And `delete` will do... – Rayon May 02 '16 at 08:23
  • That's an array of object(s). You are iterating through the array elements not the properties of first child of the array which is an object, i.e. you should iterate twice. – Ram May 02 '16 at 08:27
  • Could you add an example of the desired end product? Do you know about all the keys in the object in advance, or is that dynamic? – thriqon May 02 '16 at 08:37
  • For reference, `delete` will [**not** leave an empty slot](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/delete). – Yoshi May 02 '16 at 08:47

3 Answers3

3

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);
Jed Fox
  • 2,979
  • 5
  • 28
  • 38
Rayon
  • 36,219
  • 4
  • 49
  • 76
0

Please try this:

a = [{'id':1,'name':'James','age':11}];
b = a.map(function(v, i) {
    var copy = {};
    for(key in v) {
        if(key != 'age') {
            copy[key] = v[key];
        }
    }
    return copy;
});
Andrei
  • 42,814
  • 35
  • 154
  • 218
Sergey Gornostaev
  • 7,596
  • 3
  • 27
  • 39
-2
var a = [{'id':1,'name':'James','age':11}];

a = a.filter(function( obj,i ) {
    if(obj.hasOwnProperty('age')) {
        delete obj.age
        return obj;
    }
});
Yoshi
  • 54,081
  • 14
  • 89
  • 103
Anish Chandran
  • 427
  • 1
  • 5
  • 19