Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering an Array of Objects using Jquery $.grep without an Object Wrapper

Filtering works fine for an object (data) wrapping around an array of objects:

var arr = {"data":
 [
  {"name":"Alan","height":"171","weight":"66"},
  {"name":"Ben","height":"182","weight":"90"},
  {"name":"Chris","height":"163","weight":"71"}
 ]
};

var new_arr = $.extend(true, arr);

new_arr.data = $.grep(new_arr.data, function(n, i){
  return n.weight > 70;
});

alert(new_arr.data.length); // answer is 2

However, filtering without the object wrapper doesn't.

var arr = [
  {"name":"Alan","height":"171","weight":"66"},
  {"name":"Ben","height":"182","weight":"90"},
  {"name":"Chris","height":"163","weight":"71"}
 ];

var new_arr = $.extend(true, arr);

new_arr = $.grep(new_arr, function(n, i){
  return n.weight > 70;
});

alert(new_arr.length); // answer is 1 instead of 2

I am not sure where is the problem. Can anyone point out. Thanks!

like image 745
Question Overflow Avatar asked Dec 15 '11 13:12

Question Overflow


2 Answers

You're using extend incorrectly. You can't extend the new_arr with an array. Extend will add methods/props to an object but what methods/props will it create when it runs into your array? This is why it works with the object wrapper: 1) extend expects an object and 2) 'data' is a property that can be added to new_arry.

Despite, in your second example, it doesn't look like you need to extend anything. Does this work?

new_arr = $.grep(arr, function(n, i){ // just use arr
  return n.weight > 70;
});
like image 193
Dane O'Connor Avatar answered Oct 02 '22 00:10

Dane O'Connor


You can use this to a object more deep,

var prodIds = [];

        $.grep(this.prodOrders, function (n, i) { 

            $.grep(n.ProductionOrderLines, function (n2, i2) { 
                if (n2.ItemNo == resource) {
                    prodIds.push(n2.DocumentAbsoluteEntry);
                }
            });
        });
like image 27
David Lopes Avatar answered Oct 02 '22 02:10

David Lopes