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方法存在两个核心问题:
map方法返回的是数组,但我们需要的是对象;- 返回的对象键固定为
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
相关产品推荐
相关产品推荐

