【问题标题】:Get Unique object of JSON获取 JSON 的唯一对象
【发布时间】:2015-11-05 07:53:09
【问题描述】:

我有这种数组:

var foo = [ { "a" : "1" }, { "b" : "2" }, { "a" : "1" } ];

我想过滤它有:

var bar = [ { "a" : "1" }, { "b" : "2" }];

这是我的plunker

plunker 的第 7 行,当我写 return JSON.stringify( x ); 时它很好,但返回字符串 JSON。但是当我写 return x; 时,它变得很糟糕并且不返回唯一 JSON。

【问题讨论】:

    标签: json angularjs lodash


    【解决方案1】:

    您只需使用uniq 即可完成此操作,无需收集:

    var uniqueList =_.uniq(foo, function( x ){
        return JSON.stringify(x);
    });
    

    在此处更新 plunk:http://plnkr.co/edit/KYW6UybdiBxuvOVX8naP?p=preview

    【讨论】:

      【解决方案2】:
      first you can download underscorejs then you can use the following code
      
       var foo = [{ "a": "1" }, { "b": "2" }, { "a": "1" }];
                  var result = _.uniq(foo, function (obj) {
                      return JSON.stringify(obj);
                  });
      
      
       refere the following url  http://underscorejs.org/
      

      【讨论】:

        【解决方案3】:

        您可以使用var uniqueList =_.uniq(foo, 'a'); 这是文档:https://lodash.com/docs#uniq 这是plunker:http://plnkr.co/edit/HkirGPrs3dGZMUEnEKiT?p=preview

        【讨论】:

        • 感谢您提供非常简单的解决方案.. :)
        • 请注意,我几乎要把它作为我的答案,但意识到虽然它适用于给定的数组,但如果 b 碰巧包含重复项,它将无法工作。
        • 哇,plnkr.co/edit/oaLhZNejHXbOpSIq3El6?p=preview,我只是不确定了。 uniq 正在做一些奇怪的事情。
        • Uniq 的工作原理是:它从数组中获取元素,并通过您指向的属性将其与数组中的每个元素匹配。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-07
        • 1970-01-01
        • 1970-01-01
        • 2020-03-30
        • 1970-01-01
        • 2010-11-29
        • 1970-01-01
        相关资源
        最近更新 更多