【问题标题】:Grep return whole object instead of arrayGrep 返回整个对象而不是数组
【发布时间】: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


【解决方案1】:

如果理解正确,您希望从主对象中删除 $.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"                
   });
 });

【讨论】:

  • 你甚至不需要ab,只需将$.grep的结果赋值给this.groups即可。
  • @FábioBatista 好点,我只是想填补我认为 OP 缺少的内容
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-25
  • 2014-03-24
  • 2019-06-20
  • 2020-04-11
  • 2018-07-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多