Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get array items with customs relationship?

Tags:

javascript

I have an array which contains three items, these items are linked each other by a reference property called bound_id, this is the array:

[
   { id: "1", option: { bound_id: "2" }},
   { id: "2", option: { bound_id: "12" }},
   { id: "12", option: { bound_id: "2" }}
]

as you can see the item with id 1 is linked with the item with id 2, and the item 2 is linked to the item 12.

Now, suppose I change the value of bound_id of item 1 to null:

[
   { id: "1", option: { bound_id: null }},
   { id: "2", option: { bound_id: "12" }},
   { id: "12", option: { bound_id: "2" }}
]

how can I return all the items which are not linked each other? The expected result should be:

[
   { id: "2", option: { bound_id: "12" }}
   { id: "12", option: { bound_id: "2" }}
]

this means that the next item in the array doesn't have the relationship with the current id, so if the relationship is broken the result need to return all the items that doesn't fit any more in this relationship.

How can I achieve this?

like image 986
teres Avatar asked Mar 26 '26 14:03

teres


1 Answers

You can use filter to remove all the items which have bound_id set to null

const input = [
   { id: "1", option: { bound_id: null }},
   { id: "2", option: { bound_id: "12" }},
   { id: "12", option: { bound_id: "2" }}
];

const output = input.filter(a => a.option.bound_id);

console.log(output);
like image 122
adiga Avatar answered Mar 28 '26 05:03

adiga