You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular:如何高效将父项color属性同步到子项?

问题描述

现有对象列表:

const items: Item[]

其中Item接口定义如下:

export interface Item{
   parent?: string,
   label?: string,
   color?: string,
   isParent?: string
}

数组中包含父项与子项,示例如下:

  • 子项:
{parent: 'labelA', label: 'labelB', color: 'red', isParent: false}
  • 父项:
{parent: 'labelA', label: 'labelA', color: 'blue', isParent: true}

需求:找出所有子项,将它们的color属性更新为对应父项的color(比如上述子项的color需从red改为blue),求高效实现方式。

高效实现方案

要达到高效,核心是先构建父项的颜色映射表,避免嵌套遍历带来的O(n²)复杂度,最终实现线性时间复杂度O(n):

步骤1:构建父项颜色映射

遍历一次数组,把所有父项的label(与parent一致)和对应的color存入Map:

// 注:原接口中isParent标注为string,但示例用了布尔值,这里假设是笔误,实际为boolean;如果确实是string,将判断改为 item.isParent === "true"
const parentColorMap = new Map<string, string>();

items.forEach(item => {
  // 父项判定:isParent为true,且label与parent相同(符合示例逻辑)
  if (item.isParent === true && item.label === item.parent) {
    parentColorMap.set(item.label, item.color || '');
  }
});

步骤2:更新子项颜色

再次遍历数组,找到所有子项,通过映射表快速获取对应父项的颜色并更新:

items.forEach(item => {
  // 子项判定:isParent为false,且存在parent字段
  if (item.isParent === false && item.parent) {
    const targetColor = parentColorMap.get(item.parent);
    if (targetColor) {
      item.color = targetColor;
    }
  }
});

补充说明

  • 使用Map而非普通对象存储映射,能更好地兼容包含特殊字符的标签,且存取性能更稳定
  • 两次遍历仅需线性时间,比嵌套查找父项的方式效率提升明显
  • 如果原接口中isParent确实是字符串类型(如"true"/"false"),只需调整判断条件的取值即可

内容的提问来源于stack exchange,提问作者hawarden_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 22:05:11