javascript - 在 forEach 循环中使用动态键
问题描述
我有以下 javascript 对象
const items = {
0: {
id: 1,
color: 'blue'
},
1: {
id: 2,
color: 'red'
}
}
我正在尝试对其进行重组,以使键具有如下索引数值:item1id,item1color,item2id,item2color。或者更准确地说,它最终应该是这样的:
const restrucuturedItems = {
item1id: 1,
item1color: 'blue',
item2id: 2,
item2color: 'red'
}
我尝试了以下方法,但到目前为止没有产生积极的结果:
const restrucuturedItems = {}; // should collect the restructured data in one object like so: {item1id: 1, item1color: 'blue', item2id:2, item2color: 'red'}
const restructuredData = Object.keys(items).forEach(key => {
let i = parseInt(key, 10) + 1;
let item = {
item[i]id: 1, // this part is incorrect. it should produce item1id, item2id
item[i]color: 'blue' // this part is incorrect. it should produce item1color, item2color
}
restrucuturedItems.push(item);
});
经过数小时的研究,我仍然不知道如何正确编写这部分。
解决方案
reduce 和 map 函数可以完成这项工作
var result = Object.values(items).reduce(function (r, val) { // get all the values
var prefix = 'item' + val.id; // construct the prefix like item1, item2
Object.getOwnPropertyNames(val).map(function(key) {
r[prefix + key] = val[key]; // add to the result object
});
return r;
}, {});
推荐阅读
- python - discord.py如何给用户分配角色 v1.0 版
- javascript - 如何在antd中Form的选择组件中使用枚举进行表单验证?
- python - 从不同类别打印
- java - Java程序在eclipse中运行但在导出时不运行
- javascript - 为什么当我释放键时我的函数返回值?
- javascript - base64-jpeg 转换为 base64-png
- interface - F# 接口语法用 byref 返回的对象(或元组)声明函数,如 Int32.TryParse
- jquery - 使用 Thymaleaf 和数据库抛出异常的动态下拉菜单
- ios - CFStreamCreatePairWithSocketToHost - 如何处理网络断开连接?
- c++ - 尝试使用 winbgi 显示文本时出现编译器错误