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

JavaScript循环引用问题:构建乐器映射对象遇阻求助

解决方法:从艺术家数组构建乐器类映射对象

你的代码出现循环引用是因为错误执行了item.instrument.id = item.instrument——这行把乐器对象本身赋值给了它自己的id属性,直接造成循环引用;同时原代码用数组存储结果,也不符合预期的类映射结构。

正确实现代码

const artists = [
    {
        id: '1',
        name: 'Jimi Hendrix',
        instrument: {
            id: '1',
            name: 'Guitar',
            color: 'wood',
        }
    },
    {
        id: '2',
        name: 'Jimmy Page',
        instrument: {
            id: '1',
            name: 'Guitar',
            color: 'wood',
        }
    },
    {
        id: '3',
        name: 'Krist Novoselic',
        instrument: {
            id: '2',
            name: 'Bass',
            color: 'black',
        }
    },
    {
        id: '4',
        name: 'Emmanuelle Proulx',
    },
    {
        id: '5',
        name: 'Jimmy Chamberlin',
        instrument: {
            id: '3',
            name: 'Drums'
        }
    },
];

const result = artists.reduce((acc, artist) => {
    // 跳过没有乐器信息的艺术家
    if (!artist.instrument) return acc;
    
    // 解构分离乐器ID和其余信息
    const { id, ...instrumentDetails } = artist.instrument;
    // 避免重复添加同一ID的乐器
    if (!acc[id]) {
        acc[id] = instrumentDetails;
    }
    return acc;
}, {});

console.log(result);

代码说明

  1. 使用reduce构建对象:reduce是从数组生成类映射对象的合适工具,初始化空对象作为累加器acc
  2. 过滤无效项:跳过没有instrument属性的艺术家
  3. 解构分离属性:用对象解构提取乐器ID,同时得到去掉ID后的乐器信息,避免修改原对象
  4. 去重处理:检查累加器中是否已存在当前乐器ID,防止重复存储同一乐器

原代码问题分析

  • 误用map:map的设计目的是返回新数组,不应用来做修改外部变量的副作用操作,这类场景更适合forEach或reduce
  • 错误赋值导致循环引用:item.instrument.id = item.instrument直接修改了原对象的id属性,将乐器对象自身赋值给id,造成循环引用,正确做法是读取item.instrument.id的值而非修改它

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 16:46:29