有什麼辦法可以強制jQuery的grep函數返回新的對象與反射的新數組?例如,我有如下樣本JSON和JavaScript。grep返回整個對象,而不是數組
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。你不能把它包裹在你想要的結構中嗎? –
複製對象,創建新對象,切片元素出對象,返回對象。 – Ohgodwhy
謝謝戴夫。但我不知道如何重寫grep。你能給我提示嗎?正如我想知道如果我將重寫grep比我可能會鬆動以前的功能。 – ravi