9

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!

2 Answers 2

10

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;
});
Sign up to request clarification or add additional context in comments.

1 Comment

I just found out the reason too :) I forgot why I used extend in the first place. It seems I don't need it now. Thanks a lot :)
1

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);
                }
            });
        });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.