使用forEach循环在JS中转换数据结构

时间:2018-08-04 12:02:37

标签: javascript data-structures foreach

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

1 个答案:

答案 0 :(得分:0)

正如Xufox所说,i+1++i等效的。 如果您认为forEach不太合适,那么您可能会对reduce感兴趣:

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