为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

catspeake 2021-06-15 17:41:17
我有一个对象数组,我想避免使用特定键值重复值。这是一个对象数组。   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 返回不重复的对象。但结果似乎不同。我可以从一个对象数组中返回值。但是,我觉得从数组数组中提取值很困难。如何分配数组的过滤器数组?任何帮助,将不胜感激。提前致谢。   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 回答

?
慕森王

TA贡献1777条经验 获得超3个赞

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


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)


查看完整回答
反对 回复 2021-06-18
  • 1 回答
  • 0 关注
  • 123 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信