首页 > 解决方案 > 在 forEach 循环中使用动态键

问题描述

我有以下 javascript 对象

const items = {
    0: {
        id: 1,
        color: 'blue'
    },
    1: {
        id: 2,
        color: 'red'
    }
}

我正在尝试对其进行重组,以使键具有如下索引数值:item1iditem1coloritem2iditem2color。或者更准确地说,它最终应该是这样的:

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);
});

经过数小时的研究,我仍然不知道如何正确编写这部分。

标签: javascriptforeachkeyjavascript-objects

解决方案


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;
}, {});

https://jsfiddle.net/vw49g8t2/7/


推荐阅读