我有以下列表
javascript
-
[
{
"id" : 111,
"type": "BASE",
"someOtherProp": "other",
"linkedId": 222
},
{
"id" : 222,
"type": "CHILD",
"someOtherProp": "other",
"linkedId": 111
},
{
"id" : 333,
"type": "SOMEOTHERTYPE",
"someOtherProp": "other",
"linkedId": 444
}
]
我想签入列表,如果
type === 'BASE'
,获取匹配类型的linkedId
,并签入同一列表,如果CHILD
存在。如果 CHILD
不存在则中断循环
并抛出异常或警告消息。
注意:BASE 的对象
linkedId
是 CHILD 的对象 id
。
我计划使用嵌套循环,但正在寻找更好的方法(如果有的话)。
谢谢你。
您可以通过使用
Map
存储对对象的 id
的引用来避免嵌套循环,从而更轻松、更快速地查找相关对象。这是使用 reduce
和 Map
的方法:
const items = [
{
id: 111,
type: "BASE",
someOtherProp: "other",
linkedId: 222
},
{
id: 222,
type: "CHILD",
someOtherProp: "other",
linkedId: 111
},
{
id: 333,
type: "SOMEOTHERTYPE",
someOtherProp: "other",
linkedId: 444
}
];
// Create a map of the items based on their `id`
const itemMap = items.reduce((map, item) => {
map.set(item.id, item);
return map;
}, new Map());
// Find and check BASE and linked CHILD
items.forEach(item => {
if (item.type === "BASE") {
const linkedItem = itemMap.get(item.linkedId);
if (!linkedItem || linkedItem.type !== "CHILD") {
throw new Error(`CHILD object is not present or linked to BASE with id ${item.id}`);
}
}
});
console.log("All BASE types have a corresponding CHILD");
reduce
创建一个Map
,其中id
为键,对象为值。这使您可以在恒定时间内通过 id
查找项目。forEach
迭代列表,对于每个BASE
对象,在linkedId
中查找其Map
。linkedId
存在且其type
为CHILD
,则检查通过。否则会抛出错误。这避免了嵌套循环并使用
Map
有效地执行查找。