reactjs 从对象数组中删除引用ID与javascript中同一对象数组的任何其他对象ID不匹配的对象

wfveoks0  于 2022-11-04  发布在  React
关注(0)|答案(2)|浏览(171)

我想删除那些refId id与对象数组的任何id都不匹配的对象σ,如果refId为空,则不删除它

[
  {id: 1 , refId:null, name:'jhon'},
  {id: 2 , refId:null, name:'sam'}, 
  {id: 3 , refId:1, name:'fam'},
  {id: 4 , refId:2, name:'jam'}, 
  {id: 5 , refId:16, name:'ram'}, 
  {id: 6 , refId:15, name:'nam'}
]

结果:应B:

[
  {id: 1 , refId:null, name:'jhon'}, 
  {id: 2 , refId:null, name:'sam'}, 
  {id: 3 , refId:1, name:'fam'},
  {id: 4 , refId:2, name:'jam'},
]
drkbr07n

drkbr07n1#

请使用以下代码尝试一次:

const arr1 = [
  { id: 1, refId: null, name: "jhon" },
  { id: 2, refId: null, name: "sam" },
  { id: 3, refId: 1, name: "fam" },
  { id: 4, refId: 2, name: "jam" },
  { id: 5, refId: 16, name: "ram" },
  { id: 6, refId: 15, name: "nam" },
];

console.log(
  arr1.filter((obj) => {
    return obj.refId === null || arr1.some((o) => o.id === obj.refId);
  })
);
suzh9iv8

suzh9iv82#

这里有一个树结构,如果树很小,使用过滤器或一些是好的,但如果树很大,你应该尝试用Map(字典)。

let nodes = [
  {id: 1 , refId:null, name:'jhon'},
  {id: 2 , refId:null, name:'sam'}, 
  {id: 3 , refId:1, name:'fam'},
  {id: 4 , refId:2, name:'jam'}, 
  {id: 5 , refId:16, name:'ram'}, 
  {id: 6 , refId:15, name:'nam'}
]

let dictionary = nodes.reduce((dic, node) => { dic[node.id] = true; return  dic; }, { [null]: true });
let result = nodes.filter((node) => dictionary[node.refId]);

console.log(result);

相关问题