对象数组中的重复项 [英] Duplicates in object array

查看:73
本文介绍了对象数组中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已编辑!

我有一个对象 array :

Array 0:[{id:"a1" , code:"123" , name:"a"},
         {id: "a2", code: "222" , name: "a"},
          {id: "b1", code: "433", name: "b"}]
Array 1:[{id:"a1" , code:"123" , name:"a"},
         {id: "b2", code: "211" , name: "b"},
          {id: "b1", code: "433", name: "b"}]

我想获取没有重复的名称"值的对象数组.并将其存储到另一个 array :

I want to get the array of object that has no duplicate value for "name". and store it to another array:

Result:
Array 0:{id: "b1", code: "433", name:"b"}
Array 1: {id:"a1" , code:"123" , name:"a"}

如何获取对 name 没有重复值的对象数组?我在某个线程上发现的所有内容都是从数组中删除重复项,而不是获取没有重复项的数组.预先感谢!

How can I get the array of object that has no duplicate value for name ? All I found on some thread is to remove duplicates from array and not get the array with no duplicate. Thanks in advance!

推荐答案

function filterByName(array) {
    var counts = {};

    array.forEach(function(obj) { 
        counts[obj.name] ? ++counts[obj.name] : (counts[obj.name] = 1);
    });

    return array.filter(function(obj) { 
        return counts[obj.name] === 1;
    });
}

var filteredArray1 = filterByName(array1);
var filteredArray2 = filterByName(array2);

功能说明

  1. 创建临时的 counts 对象,以保持具有相同名称的对象的计数.
  2. 使用标准 forEach 数组方法.
  3. 使用标准 filter 方法
  1. Create temporary counts object for keeping counts of object with the same name.
  2. Fill this object with data by using standard forEach method of array.
  3. Filter array by using standard filter method

UPD 如果最后我正确理解了您的问题,则需要此:

UPD You need this if I understand your question correctly at last:

var filteredArray = arrayOfArrays.map(function(arrayOfObjects) {
  return filterByName(arrayOfObjects)[0];
});

这篇关于对象数组中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆