2

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.

kris
  • 11,868
  • 9
  • 88
  • 110

5 Answers5

2

Iterate through each object in the array and call:

delete obj.local_id
nauten
  • 487
  • 1
  • 5
  • 11
1

Try This

_.each(objects, function(v) {
    delete v.local_id;
});
Yussuf S
  • 2,022
  • 1
  • 14
  • 12
1

_.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' } ]
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

As nickf states in his answer here:

    delete myJSONObject.regex;
    // or,
    delete myJSONObject['regex'];
    // or,
    var prop = "regex";
    delete myJSONObject[prop];
Community
  • 1
  • 1
  • While there is a link (albeit not to the specific answer), this adds no new information and is not tailored to the question. Take a few minutes to explain (in your own words) and/or apply the concepts found in other resources/answers - this will make the answer much better overall. – user2864740 Jun 12 '14 at 04:25
0

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.

kris
  • 11,868
  • 9
  • 88
  • 110