【问题标题】:Using dynamic keys in forEach loop在 forEach 循环中使用动态键
【发布时间】:2018-07-26 00:52:32
【问题描述】:

我有以下 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);
});

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

【问题讨论】:

    标签: javascript foreach key javascript-objects


    【解决方案1】:

    您不应该使用push,因为您希望您的restrucuturedItems 是一个对象,而不是一个数组。

    i 与括号内的id 或颜色 连接起来,并使用两个 Object.entries - 一个来获取每个对象的键和值外部对象,一个获取每个 inner 对象的键和值:

    const items = {
        0: {
            id: 1,
            color: 'blue'
        },
        1: {
            id: 2,
            color: 'red'
        }
    }
    console.log(Object.entries(items).reduce((a, [num, obj]) => {
      Object.entries(obj).forEach(([key, val]) => {
        a['item' + num + key] = val;
      });
      return a;
    }, {}));

    如果您真的想从item1id 而不是item0id 开始,那么最初增加num

    const items = {
        0: {
            id: 1,
            color: 'blue'
        },
        1: {
            id: 2,
            color: 'red'
        }
    }
    console.log(Object.entries(items).reduce((a, [num, obj]) => {
      num++;
      Object.entries(obj).forEach(([key, val]) => {
        a['item' + num + key] = val;
      });
      return a;
    }, {}));

    【讨论】:

      【解决方案2】:

      const items = {
          0: {
              id: 1,
              color: 'blue'
          },
          1: {
              id: 2,
              color: '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;
          restrucuturedItems[`item${i}id`] = 1;
          restrucuturedItems[`item${i}color`] = 'blue'
      });
      
      console.log(restrucuturedItems)

      首先,您不能在对象上使用pushpush 是一种用于数组的方法。其次,您可以使用带有反引号的模板字符串来构造您希望的属性名称

      【讨论】:

        【解决方案3】:

        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/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-07-04
          • 1970-01-01
          • 2022-12-20
          • 1970-01-01
          • 2019-11-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多