I want to delete those objectσ which refId
id that dont match with any id of array of object, if refId
is null dont delete it
[
{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'}
]
result: should 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'},
]
CodePudding user response:
Please try once with following code:
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);
})
);
CodePudding user response:
What you have here is a tree structure, if the tree is small using a filter or some is fine, but if the tree is large you should try doing it with a mapping(dictionary).
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);