kris
kris

Reputation: 12571

How to strip a key from each object in an array?

I have a JS object that looks something like this:

[{"local_id":8,"id":null,"review_name":"One"},
 {"local_id":9,"id":null,"review_name":"too"}]

I want to strip the local_id from all of the objects in the array, so I end up with this :

[{"id":null,"review_name":"One"},
 {"id":null,"review_name":"too"}]

I'm new to underscore, I thought I could use myVar = _.omit(myVar, 'local_id'); where myVar is the object above, but that does nothing.

Upvotes: 2

Views: 199

Answers (5)

Nhat Nguyen
Nhat Nguyen

Reputation: 21

As nickf states in his answer here:

    delete myJSONObject.regex;
    // or,
    delete myJSONObject['regex'];
    // or,
    var prop = "regex";
    delete myJSONObject[prop];

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239463

_.omit will work only on Objects, but you are applying it on an Array. That is why it is not working. You can apply it on each and every element of the array, like this

console.log(_.map(data, function(obj) {
    return _.omit(obj, "local_id");
}));

Output

[ { id: null, review_name: 'One' },
  { id: null, review_name: 'too' } ]

Upvotes: 1

kris
kris

Reputation: 12571

Here is my solution:

// strip "local_id" field from myVar
$.each(myVar, function(i, obj) {

  // this line needed for it to work, i don't know why
  obj = $.parseJSON(JSON.stringify(obj));   

  delete obj.local_id;  

  myVar[i] = obj;
});

Thank you Yussuf S, monte, and Nhat Nguyen for putting me on to delete, I didn't choose any of your answers because they were not enough to solve the actual problem. Thank you user2864740 for making my question clearer and tidier without changing it.

Upvotes: 0

Yussuf S
Yussuf S

Reputation: 2112

Try This

_.each(objects, function(v) {
    delete v.local_id;
});

Upvotes: 1

nauten
nauten

Reputation: 497

Iterate through each object in the array and call:

delete obj.local_id

Upvotes: 2

Related Questions