【发布时间】:2012-06-19 19:20:18
【问题描述】:
有什么方法可以强制 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"
}
]
}
]
任何想法都会有很大帮助。
【问题讨论】:
-
当然,重写 grep。你不能把它包装成你想要的结构吗?
-
复制对象,创建新对象,从对象中切出元素,返回对象。
-
谢谢戴夫。但我不确定如何重写 grep。你能给我提示吗?因为我想知道我是否会重写 grep 而不是我可能会失去以前的功能。
-
@ravi 我是在讽刺——我的意思是保持
grep不变,并将结果包装在您需要的结构中。
标签: jquery json javascript-objects