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

JavaScript中如何将数组转换为以name为键的对象

将数组转换为以对象name属性为键的对象结构

这里提供几种JavaScript中实现该转换的常用方法:

方法1:使用Array.reduce()(推荐)

这是最简洁且常用的方式,利用reduce方法逐步构建目标对象:

const arr = [
    { name: 'abc', age: 15, roll_no: 25 },
    { name: 'def', age: 10, roll_no: 20 },
    { name: 'xyz', age: 16, roll_no: 18 },
];

const obj = arr.reduce((result, currentItem) => {
    result[currentItem.name] = currentItem;
    return result;
}, {});

console.log(obj);

reduce的第一个参数是回调函数,负责将每个数组元素添加到结果对象中;第二个参数{}是初始的空对象。

方法2:使用Array.forEach()

如果更习惯循环写法,可以用forEach遍历数组并手动赋值:

const arr = [
    { name: 'abc', age: 15, roll_no: 25 },
    { name: 'def', age: 10, roll_no: 20 },
    { name: 'xyz', age: 16, roll_no: 18 },
];

const obj = {};
arr.forEach(item => {
    obj[item.name] = item;
});

console.log(obj);

方法3:使用Object.fromEntries()

ES2019及以上版本支持的方法,先把数组转成[键, 值]形式的二维数组,再转换为对象:

const arr = [
    { name: 'abc', age: 15, roll_no: 25 },
    { name: 'def', age: 10, roll_no: 20 },
    { name: 'xyz', age: 16, roll_no: 18 },
];

const obj = Object.fromEntries(arr.map(item => [item.name, item]));

console.log(obj);

arr.map()将每个元素转换为[name属性值, 原对象]的数组,Object.fromEntries()再把这个二维数组转换成目标对象。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 10:42:06