首页 > 解决方案 > 用forEach循环转换JS中的数据结构

问题描述

const inputformat = [
  {date: "2018-08-01", round: 1},
  {date: "2018-08-01", round: 2},
  {date: "2018-08-01", round: 3},
  {date: "2018-08-02", round: 1},
]

outputformat = {
  "2018-08-01": [1,2,3],
  "2018-08-02": [1]
}

在 JS 中我想将 inputformat 转换为 outputformat,我想出了下面的解决方案。

但是我的逻辑出了点问题,也许是 if 条件。控制台错误消息说无法读取未定义的属性“日期”,但我已经检查了下一个项目是否存在,arr[i] && arr[++i]任何人都可以帮助我解决这个问题。非常感谢~

let outputformat = {}
inputformat.forEach((k, i, arr)=> {
  const date = k.date
  const round = [k.round]
    if (arr[i] && arr[++i] && arr[i].date === arr[++i].date) {
      outputformat[date] = round.push(arr[++i].round)
    }else{
      outputformat[date] = round
    }
})

标签: javascriptdata-structuresforeach

解决方案


正如Xufox所说,i+1并不++i等同。在您的情况下并不合适,您可能对以下内容更感兴趣:forEachreduce

const outputFormat = inputFormat.reduce((acc, {date, round})=>{
  const newVal = acc[date] ? Array.concat(acc[date], round) : [round];
  /*if(acc[date])
    return Object.assign({}, acc, {
      [date]: Array.concat(acc[date], round)
    })*/

  return Object.assign({}, acc, {
    [date]: newVal//[round]
  });
}, {});

或者

const outputFormat = inputFormat.reduce((acc, {date, round})=>{
  if(!acc[date])
    acc[date] = [];

  acc[date].push(round);
  return acc;
}, {});

推荐阅读