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

遍历嵌套对象数组仅获首个spec项,如何转换为目标简化结构?

嵌套对象结构转换解决方法

问题背景

你拥有如下嵌套结构的对象:

var arr = {
  specss: [{
      moe: 1,
      spec: [{
          specID: 4,
          cat: [{
              catID: 6,
            }],
        },
        {
          specID: 11,
          cat: [{
              catID: 7,
            }],
        }],
    }],
};

尝试转换为更简洁的结构时,遍历仅能获取spec中的第一个项,目标输出为:

[{
    moe: 1,
    spec: [
      {
        specID: 4,
        catID: 6,
      },
      {
        specID: 11,
        catID: 7,
      },
    ],
  }];

解决代码

通过两层map遍历就能完整处理所有spec项,代码如下:

const result = arr.specss.map(item => ({
  moe: item.moe,
  spec: item.spec.map(specItem => ({
    specID: specItem.specID,
    catID: specItem.cat[0].catID
  }))
}));

console.log(result);

代码说明

  • 第一层map遍历specss数组中的每个元素,保留原有的moe字段。
  • 第二层map遍历每个元素下的spec数组,重组每个spec对象:保留specID,同时从cat数组的第一个元素中提取catID(若cat数组存在多个元素,可根据需求调整提取逻辑)。
  • map方法会返回全新数组,不会修改原始对象结构,更安全可控。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 04:40:34