【问题标题】:How to keep only unique object in an array of objects using javascript如何使用javascript在对象数组中仅保留唯一对象
【发布时间】:2016-07-21 09:53:57
【问题描述】:

我正在像这样从服务器获取响应

{
    owners:[
    {
    _id:"33333"
    email:test1@gmail.com
    }
    {
    _id:"1111"
    email:test2@gmail.com
    }]
    employee:[
     {
    _id:"44342"
    email:test1@gmail.com
    }
    {
    _id:"35345"
    email:test3@gmail.com
    }
     {
    _id:"3556"
    email:test4@gmail.com
    }
    ]
    users:[
    {
    _id:"56744"
    email:test5@gmail.com
    }
    {
    _id:"8908"
    email:test4@gmail.com
    }]
}

我想保留在所有对象数组中只有唯一 email id 的对象,结果应该是这样的:

{
    owners:[
    {
    _id:"33333"
    email:test1@gmail.com
    }
    {
    _id:"1111"
    email:test2@gmail.com
    }]
    employee:[

    {
    _id:"35345"
    email:test3@gmail.com
    }
     {
    _id:"35345"
    email:test4@gmail.com
    }
    ]
    users:[
    {
    _id:"56744"
    email:test5@gmail.com
    }
]
}

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 您要保留哪些重复记录,第一个?因为 _id 是唯一的,inof 将永远丢失。

标签: javascript node.js underscore.js lodash


【解决方案1】:

由于您希望两个数组具有唯一性,因此您必须先将它们组合起来。

let combined = result.owners.map(o => {o.type = 'owner'; return o;})
            .concat(result.users.map(u => {u.type = 'user'; return u;});
combined = _.uniqBy(combined, 'email');

result.owners = _.filter(combined, {type: 'owner');
result.users = _.filter(combined, {type: 'user');

员工也是如此。

【讨论】:

    【解决方案2】:

    嗯,有几种方法可以做到这一点。最简单的方法之一是使用 lodashunderscore 之类的库,并使用 uniq 方法根据属性过滤掉重复的对象。

    以下划线为例,获取所有者对象的唯一列表:

    _.uniq(owners, 'email')

    或者这种功能也可以工作:

    function uniqeValues(objects, property) {
         let unique_values = {};
    
         objects.forEach(object=> {
             if (!unique_values.hasOwnProperty(object[property])) {
                 unique_values[object[property]] = object;
             }
         });
    
         return Object.values(unique_values);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      相关资源
      最近更新 更多