javascript - 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"}
。如何将键转换为整数?
解决方案
为了说明@MarkMeyer 的评论:
键只能是 javascript 对象中的字符串(或符号)。
console.log({3: 4, '3': 5});
推荐阅读
- r - 基于多个条件的多列中特定数字的移动概率和移动平均值
- amazon-web-services - 文件上传到 AWS S3 引发 javax.net.ssl.SSLHandshakeException
- r - R中的YOLO暗网训练
- angular - Mat-Option 显示选项但单击时不选择
- c# - 在坏驱动器上运行 DriveInfo.IsReady 超时后如何中止thead
- javascript - 如何使用javascript在数据库表(html)中只下载想要的数据?
- javascript - 毕达哥拉斯公式在Javascript中计算三角形的周长?
- kubernetes - 变压器功能不适用于 Seldon Core
- reactjs - 如何在 Preact 无状态组件上键入属性“键”
- unix - 打印从 foreach 循环中完成的任务百分比