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

JS数组转对象:如何以指定属性值为键?解决Object.assign索引问题

解决数组转指定键值对象的问题

嗨,我刚好遇到过类似的场景,这就帮你搞定!你之前用Object.assign({}, ...arr)不行,是因为直接展开数组元素的话,这些元素本身没有可识别的键名,所以会默认按数组索引来处理,自然达不到你要的效果。

这里有两种简单的方法可以实现你的需求:

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

reduce是处理这种结构转换的利器,逻辑清晰且高效:

const arr = [
  { "description": "red", "type": "fruit", "item": "apple" },
  { "description": "yellow", "type":"fruit", "item": "banana" }
];

const transformedObj = arr.reduce((accumulator, currentItem) => {
  // 解构出item字段,剩下的属性存入rest
  const { item, ...rest } = currentItem;
  // 以item为键,把rest赋值给累加器
  accumulator[item] = rest;
  return accumulator;
}, {}); // 初始值设为空对象

console.log(transformedObj);
// 输出结果:
// {
//   "apple": { "description": "red", "type": "fruit" },
//   "banana": { "description": "yellow", "type": "fruit" }
// }

逻辑解释

  • 我们从每个数组元素里把item字段单独拿出来,剩下的属性用...rest收集起来
  • 把item的值作为新对象的键,rest作为对应的值存入累加器
  • 遍历完所有元素后,累加器就是我们要的最终对象

方法二:Array.map + Object.assign

如果你更习惯用Object.assign,可以先把每个数组元素转换成{ [item]: rest }的格式,再合并:

const arr = [
  { "description": "red", "type": "fruit", "item": "apple" },
  { "description": "yellow", "type":"fruit", "item": "banana" }
];

const transformedObj = Object.assign(
  {},
  ...arr.map(obj => {
    const { item, ...rest } = obj;
    return { [item]: rest };
  })
);

console.log(transformedObj);
// 输出和上面完全一致

逻辑解释

  • 先用map把每个元素转成一个只有单个键值对的对象,键是item的值,值是去掉item后的剩余属性
  • 再把这些小对象展开,用Object.assign合并成一个大对象

两种方法都能完美实现你的需求,看你个人习惯选择就好~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:58:10