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

如何用一行代码将指定数组转换为目标对象?

数组转目标对象的一行代码实现

这里提供两种符合要求的一行代码实现方式:

方式一:使用reduce方法

const arr = [{type: 'fruit', value: 'apple'}, {type: 'meat', value: 'pig'}, {type: 'vegetable', value: 'carrot'}, {type: 'desert', value: 'cake'}];
const targetObj = arr.reduce((acc, { value }) => ({ ...acc, [value]: true }), {});

通过reduce遍历原数组,每次解构出元素的value属性,利用对象扩展运算符将累加对象与当前value: true的键值对合并,初始累加值设为空对象,最终得到目标结构。

方式二:使用Object.fromEntries结合map

const arr = [{type: 'fruit', value: 'apple'}, {type: 'meat', value: 'pig'}, {type: 'vegetable', value: 'carrot'}, {type: 'desert', value: 'cake'}];
const targetObj = Object.fromEntries(arr.map(item => [item.value, true]));

先通过map将原数组的每个元素转换为[value, true]格式的键值对数组,再用Object.fromEntries将这个二维数组直接转换为目标对象,代码更简洁直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:55:22