简体   繁体   English

如何获得具有海关关系的数组项目?

[英]How to get array items with customs relationship?

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: 我有一个包含三个项目的数组,这些项目通过名为bound_id的引用属性相互链接,这是数组:

[
   { 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 . 如您所见,ID为1的项目与ID为2的项目相关联,项目2与项目12相关联。

Now, suppose I change the value of bound_id of item 1 to null : 现在,假设我将item 1bound_id的值更改为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. 这意味着数组中的下一个项目与当前id没有关系,因此如果关系被破坏,结果需要返回此关系中不再适合的所有项目。

How can I achieve this? 我怎样才能做到这一点?

You can use filter to remove all the items which have bound_id set to null 您可以使用filter删除bound_id设置为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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM