如何在多个条件下过滤对象数组并添加异常?

How to filter array of objects on multiple conditions and add exception?

我目前有一组根据唯一 ID 和唯一名称一起过滤的对象:

初始输入:

const data = [
  {
    id: 1234,
    name: "Name1"
  },
  {
    id: 1234,
    name: "Name1"
  },
  {
    id: 1234,
    name: "Name2"
  },
  {
    id: 1234,
    name: null
  },
  {
    id: 5678,
    name: "Name3"
  },
  {
    id: 5678,
    name: "Name3"
  },
  {
    id: 5678,
    name: null
  },
  {
    id: 9999,
    name: null
  },
  {
    id: 9999,
    name: null
  },
];
data.filter((value, index, self) => {
      return (
        self.findIndex(
          (v) =>
            v.id === value.id &&
            v.name=== value.name
        ) === index
      );
});
  [
      {
        id: 1234
        name: "Name1"
      },
      {
        id: 1234
        name: "Name2"
      },
      {
        id: 1234
        name: null
      },
      {
        id: 5678
        name: null
      },
      {
        id: 5678
        name: "Name3"
      },
      {
        id: 9999
        name: null
      },
  ]

但是,有些 ID 没有任何重复项,我想删除所有空名称关联对象,但 ID 不重复且如下所示的对象除外:

  [
      {
        id: 1234
        name: "Name1"
      },
      {
        id: 1234
        name: "Name2"
      },
      {
        id: 5678
        name: "Name3"
      },
      {
        id: 9999
        name: null
      },
  ]

目前空名称的重复ID仍然存在。

我将您实现的过滤部分保留为中间输出。使用它我得到了每个 id 的计数。然后使用它我从中间数组中过滤掉,如果有计数> 1并且有一个空名称我删除它。

 const data = [{id: 1234,name: "Name1"},{id: 1234,name: "Name1"},{id: 1234,name: "Name2"},{id: 1234,name: null},{id: 5678,name: "Name3"},{
id: 5678,name: "Name3"},{id: 5678,name: null},{id: 9999,name: null},{id: 9999,name: null},];
  
//filtering out duplicates
let a = data.filter((value, index, self) => {
      return (
        self.findIndex(
          (v) =>
            v.id === value.id &&
            v.name=== value.name
        ) === index
      );
});
    
  //get count for ids in partially filtered 
let idcount = a.reduce((acc,curr) => {
    if(!acc[curr.id])acc[curr.id] = 0
  acc[curr.id] += 1
  return acc;
},{})

//remove the duplicate nulls
let final = a.filter((el) => {
    return !(idcount[el.id]>1 && el.name===null)
})


console.log(final)