Filtering an array of objects using jquery $ .grep without a object fairing

Filtering works great for an object ( data ) wrapping 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 wrapping the object is not performed.

 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 the problem is. Can someone point out. Thanks!

+8
javascript jquery filtering
source share
2 answers

You are using extension incorrectly. You cannot extend new_arr with an array. The extension will add methods / details to the object, but what methods / details will be created when launched into your array? That's why it works with the wrapper of an object: 1) expects an object to be expanded and 2) "data" is a property that can be added to new_arry.

Even though in your second example it doesn't seem like you need to extend anything. It works?

 new_arr = $.grep(arr, function(n, i){ // just use arr return n.weight > 70; }); 
+8
source share

You can use this for a deeper object,

 var prodIds = []; $.grep(this.prodOrders, function (n, i) { $.grep(n.ProductionOrderLines, function (n2, i2) { if (n2.ItemNo == resource) { prodIds.push(n2.DocumentAbsoluteEntry); } }); }); 
0
source share

All Articles