从数组的数组中删除重复的值

时间:2019-06-03 18:18:06

标签: javascript list validation duplicates

我有一个对象数组,我想避免使用特定的键值重复值。

这是一个objectArray。

   var dept = 
 [
    {
  "department": [
    { "userName": "cds",
      "userId": "33",
      "userFirstname": "Chef",
      "userLastname": "Jone"
    },
    {
      "userName": "asset1",
      "userId": "27",
      "userFirstname": "Asset",
      "userLastname": "Ann "
    }
  ],
  "comment": "",
  "doc": null
},
{
  "department": [
    { 
      "userName": "audit1",
      "userId": "32",
      "userFirstname": "Audit",
      "userLastname": "Kim"
    },
    { "userName": "cds",
      "userId": "33",
      "userFirstname": "Chef",
      "userLastname": "Jone"
    }
  ],
  "comment": "",
  "doc": null
    }
 ];

我试图通过javascript返回未重复的对象。 但是结果似乎有所不同。 我可以从一个对象数组返回值。但是,我感到很难从array的数组中提取值。 如何分配数组的过滤器数组? 任何帮助,将不胜感激。 预先感谢。

   function getUnique(dept, comp) { 

  const unique = dept
   .map(e => e[comp])

 // store the keys of the unique objects
.map((e, i, final) => final.indexOf(e) === i && i)

// eliminate the dead keys & store unique objects
.filter(e => dept[e]).map(e => dept[e]);

  return unique;
  }

return getUnique(dept,'userName');

我会得到结果

 [
{
  "department": [
    { "userName": "cds",
      "userId": "33",
      "userFirstname": "Chef",
      "userLastname": "Jone"
    },
    {
      "userName": "asset1",
      "userId": "27",
      "userFirstname": "Asset",
      "userLastname": "Ann "
    }
  ],
  "comment": "",
  "doc": null
},
{
  "department": [
    { 
      "userName": "audit1",
      "userId": "32",
      "userFirstname": "Audit",
      "userLastname": "Kim"
    } 
  ],
  "comment": "",
  "doc": null
    }
  ];

但是,我得到了结果

   [
    {
"department": [
 { "userName": "cds",
    "userId": "33",
    "userFirstname": "Chef",
    "userLastname": "Jone"
 },
 {
      "userName": "asset1",
      "userId": "27",
      "userFirstname": "Asset",
      "userLastname": "Ann "
  }
],
"comment": "",
"doc": null
  }
]

1 个答案:

答案 0 :(得分:1)

您可以结合使用地图和过滤器

var dept =[{"department": [{ "userName": "cds","userId": "33","userFirstname": "Chef","userLastname": "Jone"},{"userName": "asset1","userId": "27","userFirstname": "Asset","userLastname": "Ann "}],"comment": "","doc": null},{ "department": [{ "userName": "audit1","userId": "32","userFirstname": "Audit","userLastname": "Kim"},{ "userName": "cds","userId": "33","userFirstname": "Chef","userLastname": "Jone"}],"comment": "","doc": null}];
 
let tracker = {}
let op = dept.map(val => {
  let department = val.department
  let filtered = department.filter(({userId}) => {
    if(tracker[userId] !== undefined ){
      return false
    } else {
      tracker[userId] = userId
      return true
    }
  })
  return {...val,department: filtered}
})

console.log(op)