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

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


这是一个对象数组。


   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

  }

]


catspeake
浏览 125回答 1
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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript