有没有办法可以强制jquery的grep函数返回带有反射新数组的新对象?例如,我有样本JSON和javascript,如下所示。
var myObject = { "Apps" : [
{
"Name" : "app1",
"id" : "1",
"groups" : [
{ "id" : "1",
"name" : "test group 1",
"desc" : "this is a test group"
},
{ "id" : "2",
"name" : "test group 2",
"desc" : "this is another test group"
},
{ "id" : "2",
"name" : "test group 2",
"desc" : "this is another test group"
}
]
}
]
}
var b,a;
$.each(myObject.Apps, function() {
b = $.grep(this.groups, function(el, i) {
return el.id.toLowerCase() === "2"
});
});
alert(JSON.stringify(b));
所以一旦我运行这个,我会按照预期得到警告中的文字。
[{"id":"2","name":"test group 2","desc":"this is another test group"},{"id":"2","name":"test group 2","desc":"this is another test group"}]
但我希望这个新的返回数组的整个javascript对象是这样的。 预期O / p ::
"Apps" : [
{
"Name" : "app1",
"id" : "1",
"groups" : [
{ "id" : "2",
"name" : "test group 2",
"desc" : "this is another test group"
},
{ "id" : "2",
"name" : "test group 2",
"desc" : "this is another test group"
}
]
}
]
任何想法都会有很大的帮助。
答案 0 :(得分:4)
如果理解正确,您想从主对象中删除$ .grep中未返回的任何组。
使用$.grep()
方法在$.each
之后的$.grep
循环中添加一行
DEMO:http://jsfiddle.net/67Bbg/
var b,a;
$.each(myObject.Apps, function() {
b = $.grep(this.groups, function(el, i) {
return el.id.toLowerCase() === "2"
});
/* replace group with new array from grep */
this.groups=b;
});
编辑:缩写版
$.each(myObject.Apps, function() {
this.groups= $.grep(this.groups, function(el, i) {
return el.id.toLowerCase() === "2"
});
});