使用 Jquery $.grep 过滤对象数组而不使用对象包装器
过滤对于包装对象数组的对象 (data
) 效果很好:
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
但是,没有对象包装器的过滤则不然。
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
我不确定问题出在哪里。谁能指点一下。谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您错误地使用了 extend 。您不能使用数组扩展 new_arr 。 Extend 会将方法/道具添加到对象中,但是当它遇到数组时它将创建哪些方法/道具?这就是它与对象包装器一起使用的原因:1)extend 需要一个对象,2)“data”是一个可以添加到 new_arry 的属性。
尽管如此,在您的第二个示例中,您似乎不需要扩展任何内容。这有效吗?
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?
您可以将其用于更深入的对象,
You can use this to a object more deep,