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

如何从对象与数组创建并分组目标数组?

如何将商品特征与对应值分组为目标结构

我有一个itemAttributes对象,其中每个键是商品特征(颜色、尺寸或材质)的ID,对应值为特征值(红色、蓝色等)的ID数组。另外还有两个数组:arr1存储特征的标题与ID对应关系,arr2存储特征值的标题、所属特征ID和自身ID。需要将这些数据转换为resultArray的结构,尝试用reduce函数但未得到预期结果,请问该如何实现?

原始数据

const itemAttributes = { "11": [19,20], "12": [21,22,23], "13": [25,26,27] };

const arr1 = [ 
  {title: "colors", id: 11 }, 
  {title: "sizes", id: 12 }, 
  {title: "materials", id: 13 }
];

const arr2 = [ 
  {title: "red", attribute: 11, id: 19 },
  {title: "blue", attribute: 11, id: 20 }, 
  {title: "10x20", attribute: 12, id: 21 }, 
  {title: "10x30", attribute: 12, id: 22 },
  {title: "10x40", attribute: 12, id: 23 },
  {title: "10x50", attribute: 12, id: 24 },
  {title: "metals", attribute: 13, id: 25 },
  {title: "polymers", attribute: 13, id: 26 },
  {title: "ceramics", attribute: 13, id: 27 },
];

目标结构

const resultArray = [
  {
    title: "colors",
    items: ["red", "blue"],
  },
  {
    title: "sizes",
    items: ["10x20", "10x30", "10x40"],
  },
  {
    title: "materials",
    items: ["metals", "polymers", "ceramics"],
  }
];

解决方案

方法一:预构建映射表(高效推荐)

先通过reduce构建两个映射表,将数组转换为键值对形式,后续查找时可以直接通过ID获取对应标题,避免重复遍历数组,提升性能。

// 构建特征ID到标题的映射
const attributeTitleMap = arr1.reduce((map, item) => {
  map[item.id] = item.title;
  return map;
}, {});

// 构建特征值ID到标题的映射
const valueTitleMap = arr2.reduce((map, item) => {
  map[item.id] = item.title;
  return map;
}, {});

// 生成结果数组
const resultArray = Object.entries(itemAttributes).map(([attrId, valueIds]) => ({
  title: attributeTitleMap[attrId],
  items: valueIds.map(id => valueTitleMap[id])
}));

方法二:直接遍历查找(简单直观)

如果数据量较小,可以直接在遍历过程中用find方法查找对应标题,代码更简洁但性能略差。

const resultArray = Object.entries(itemAttributes).map(([attrId, valueIds]) => ({
  title: arr1.find(item => item.id == attrId).title,
  items: valueIds.map(id => arr2.find(item => item.id == id).title)
}));

方法三:用reduce实现(针对你的需求)

如果偏好使用reduce,可以遍历arr1,结合itemAttributes和arr2生成结果:

const resultArray = arr1.reduce((acc, attr) => {
  // 获取当前特征对应的所有值ID
  const valueIds = itemAttributes[attr.id];
  if (valueIds) {
    // 找到每个值ID对应的标题
    const items = valueIds.map(id => arr2.find(v => v.id === id).title);
    acc.push({ title: attr.title, items });
  }
  return acc;
}, []);

内容的提问来源于stack exchange,提问作者tako-sphynx

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 06:36:32