0

有什么办法可以强制 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"
             }
        ]              
    }
    ]

任何想法都会有很大帮助。

4

1 回答 1

4

如果理解正确,您希望从主对象中删除 $.grep 中未返回的任何组。

使用您的方法在循环$.grep()中添加一行之后$.each$.grep

演示: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"                
   });
 });
于 2012-06-19T21:52:47.757 回答