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

如何将对象数组转换为以dataType为键、dataValue为值的单一对象?

实现数组转目标对象的几种方法

你说的这种把对象数组转换成键值对对象的需求很常见,我给你整理几个实用的实现方式:

方法一:补全你尝试的forEach写法

你之前试了forEach但没完成,其实只需要初始化一个空对象,然后在循环里给对象逐个赋值就行:

const arr = [
  { dataType: 'something', dataValue: 'book' },
  { dataType: 'food', dataValue: 'brocolli' },
  { dataType: 'object', dataValue: 'chair' }
];

const result = {};
arr.forEach(item => {
  // 把每个item的dataType作为键,dataValue作为值
  result[item.dataType] = item.dataValue;
});

console.log(result); 
// 输出: { something: 'book', food: 'brocolli', object: 'chair' }

方法二:用Array.reduce(更紧凑的函数式写法)

reduce天生适合这种“把数组浓缩成单一值”的场景,代码更简洁:

const arr = [
  { dataType: 'something', dataValue: 'book' },
  { dataType: 'food', dataValue: 'brocolli' },
  { dataType: 'object', dataValue: 'chair' }
];

const result = arr.reduce((acc, item) => {
  acc[item.dataType] = item.dataValue;
  return acc;
}, {}); // 第二个参数是初始值,这里是空对象

console.log(result);
// 输出和上面一致

方法三:用Object.fromEntries(ES2019+ 极简写法)

如果你的运行环境支持ES2019及以上,这种写法最清爽:先把原数组转换成[key, value]格式的二维数组,再用fromEntries直接转成对象:

const arr = [
  { dataType: 'something', dataValue: 'book' },
  { dataType: 'food', dataValue: 'brocolli' },
  { dataType: 'object', dataValue: 'chair' }
];

const result = Object.fromEntries(
  arr.map(item => [item.dataType, item.dataValue])
);

console.log(result);
// 同样得到目标对象

这几种方法都能实现你的需求,你可以根据项目的环境和自己的习惯来选~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:13:30