用同一列表中对象的另一个属性检查对象属性的更好方法

问题描述 投票:0回答:1

我有以下列表

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

我计划使用嵌套循环,但正在寻找更好的方法(如果有的话)。

谢谢你。

javascript
1个回答
0
投票

您可以通过使用

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");

解决问题的有效方法:

  1. 创建地图:使用
    reduce
    创建一个
    Map
    ,其中
    id
    为键,对象为值。这使您可以在恒定时间内通过
    id
    查找项目。
  2. 单次迭代:使用
    forEach
    迭代列表,对于每个
    BASE
    对象,在
    linkedId
    中查找其
    Map
  3. 检查条件:如果
    linkedId
    存在且其
    type
    CHILD
    ,则检查通过。否则会抛出错误。

这避免了嵌套循环并使用

Map
有效地执行查找。

© www.soinside.com 2019 - 2024. All rights reserved.