Return 关于 属性 的唯一性的对象数组:Javascript

Return array of objects with respect to uniqueness of property: Javascript

我有具有以下结构的对象数组

const arr = [
              {id: 0, name: "abc", userid: "0"},
              {id: 1, name: "lmn", userid: "123"},
              {id: 3, name: "pqr", userid:"456"},
              {id: 4, name: "xyz", userid: "123"}
            ]

我想要 return userid 应该唯一且不等于“0”的对象。

这是我的方法。 return就是一切

   const result = [
        ...new Set(
             arr.map((node) => {
            if (node.userid !== "0") return node;
          })
        )
      ];
      console.log(result);

也许我可以用更 short-hand 的方式来完成,但它是这样工作的:

const arr = [
          {id: 0, name: "abc", userid: "0"},
          {id: 1, name: "lmn", userid: "123"},
          {id: 3, name: "pqr", userid: "456"},
          {id: 4, name: "xyz", userid: "123"}
        ];

const clearZero = arr.filter((obj) => obj.id != 0);
const finalArray = [];

clearZero.forEach((obj) => {
  if (finalArray.every((elem) => elem.userid !== obj.userid)) {
    finalArray.push(obj);
  }
})

console.log(finalArray); // logs out no. 1 and no.3

不使用 Set,而是使用 Map。两者都用于存储唯一值,它们之间的区别是 Set 用于具有唯一值的数组,而 Map 用于具有唯一键的对象。

const arr = [
  {id: 0, name: "abc", userid: "0"},
  {id: 1, name: "lmn", userid: "123"},
  {id: 3, name: "pqr", userid: "456"},
  {id: 4, name: "xyz", userid: "123"}
];
const result = new Map()
arr.forEach(node => {
  if(node.userid !== "0"){
    result.set(node.userid,node);
  }
})
console.log([...result.values()]); // log intended results

对于简写的解决方案,您可以使用:

const result = [...new Map(arr.filter(node=>node.userid!=="0").map(node=>[node.userid, node])).values()];
console.log(result) // log intended results