Grep返回整个对象而不是数组

时间:2012-06-19 19:20:18

标签: jquery json javascript-objects

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

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

1 个答案:

答案 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"                
   });
 });