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

创建嵌套结构对象数组时,添加内部对象意外生成新外层对象的问题求助

问题分析与解决:重复创建外层对象的bug

你的代码核心问题在于错误的存在性判断逻辑,以及每次循环都重新创建外层对象,导致相同首字母的商品被分到了不同的外层对象里。咱们一步步拆解问题:

问题出在哪?

  1. 判断逻辑错误:catalogue.includes(catalogueLetter)这行完全不对——catalogue数组里存的是{name: 'C', items: []}这样的对象,不是单个字符,所以这个判断永远返回false,每次循环都会往数组里push新的外层对象。
  2. 重复创建对象:你每次循环都新建let obj = { name: name[0], items: [] },哪怕之前已经有相同首字母的外层对象,你也没复用它,而是把当前商品加到了新对象的items里。

修正后的代码

function catalogue(input) { 
  let catalogue = []; 
  for (let line of input) { 
    let [name, price] = line.split(" : ") 
    let catalogueLetter = name[0]; 
    
    // 先在已有数组里找对应首字母的外层对象
    let existingObj = catalogue.find(item => item.name === catalogueLetter);
    
    let obj;
    if (!existingObj) {
      // 找不到才创建新对象并加入数组
      obj = { name: catalogueLetter, items: [] };
      catalogue.push(obj);
    } else {
      // 找到就直接复用已有对象
      obj = existingObj;
    }
    
    let innerObject = { productName: name, productPrice: price };
    obj.items.push(innerObject);
  }
  // 记得返回结果,不然看不到输出
  return catalogue;
} 

// 测试一下
console.log(catalogue([ 'Omlet : 5.4', 'Shirt : 15', 'Cake : 59', 'Carrot : 2' ]));

优化版本(更高效)

如果处理的数据量比较大,用Array.find()每次遍历数组效率不高,可以用对象做映射来优化:

function catalogue(input) { 
  let letterMap = {};
  let catalogue = [];
  
  for (let line of input) { 
    let [name, price] = line.split(" : ") 
    let letter = name[0];
    
    if (!letterMap[letter]) {
      let obj = { name: letter, items: [] };
      letterMap[letter] = obj;
      catalogue.push(obj);
    }
    
    // 直接通过映射找到对象,添加商品
    letterMap[letter].items.push({ productName: name, productPrice: price });
  }
  
  // 可选:按字母顺序排序外层对象
  catalogue.sort((a, b) => a.name.localeCompare(b.name));
  
  return catalogue;
}

最终结果

运行修正后的代码,就能得到你期望的结构:

[
  { name: 'C', items: [
      { productName: 'Cake', productPrice: '59' },
      { productName: 'Carrot', productPrice: '2' }
    ]
  },
  { name: 'O', items: [ { productName: 'Omlet', productPrice: '5.4' } ] },
  { name: 'S', items: [ { productName: 'Shirt', productPrice: '15' } ] }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 18:32:36