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

JavaScript:将嵌套数组转换为指定结构对象组的方法

数组转指定结构对象的实现方案

原始数组结构

const arr = [
  {field: "f1", values: [{ count:1, value: "a"}, { count:2, value: "b"}] },
  {field: "f2", values: [{ count:3, value: "c"}, { count:4, value: "d"}] }
];

期望输出结构

const output = {
  f1: { name: "f1", selected: [] },
  f2: { name: "f2", selected: [] }
};

需求说明

将数组中每个元素的field字段值作为新对象的键,对应的值为包含name属性(值与field字段一致)和空selected数组的对象。

错误代码问题分析

你尝试的map方法存在两个核心问题:

  1. map方法返回的是数组,但我们需要的是对象;
  2. 返回的对象键固定为item,且name属性错误赋值为整个item对象,而非item.field的值。

正确实现方法

方法1:使用reduce(推荐,数组转对象的标准方式)

const output = arr.reduce((result, currentItem) => {
  result[currentItem.field] = {
    name: currentItem.field,
    selected: []
  };
  return result;
}, {});

方法2:使用forEach(直观易懂)

const output = {};
arr.forEach(item => {
  output[item.field] = { name: item.field, selected: [] };
});

以上两种方法均能生成符合需求的对象结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 04:20:22