首页 > 解决方案 > Javascript数组reduce将数组转换为具有整数键的对象

问题描述

我正在尝试使用 reduce 方法将对象数组转换为对象。问题是我想要数字的对象键。

let crops = [{
  id: 1,
  name: "wheat"
}, {
  id: 2,
  name: "rice"
}];

let cropsObj = crops.reduce((accumulator, currentValue) => {
  accumulator[currentValue.id] = currentValue.name
  return accumulator;
}, {});

console.log(cropsObj);

这很好用,除了我得到的键是字符串。例如:

{"1":"wheat","2":"rice"}

我想要的是 {1:"wheat",2:"rice"}。如何将键转换为整数?

标签: javascriptobjectecmascript-6

解决方案


为了说明@MarkMeyer 的评论:

键只能是 javascript 对象中的字符串(或符号)。

console.log({3: 4, '3': 5});


推荐阅读