Javascript 使用 Jquery $.grep 过滤对象数组而不使用对象包装器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8521127/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filtering an Array of Objects using Jquery $.grep without an Object Wrapper
提问by Question Overflow
Filtering works fine for an object (data
) wrapping around an array of objects:
过滤适用于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
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!
我不确定问题出在哪里。谁能指点一下。谢谢!
回答by Dane O'Connor
You're using extendincorrectly. 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.
您使用的扩展不正确。你不能用数组扩展 new_arr 。Extend 将向对象添加方法/道具,但是当它运行到您的数组时会创建什么方法/道具?这就是它与对象包装器一起工作的原因:1)extend 需要一个对象,2)'data' 是一个可以添加到 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;
});
回答by David Lopes
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);
}
});
});