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!
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;
});
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);
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With