简体   繁体   中英

transform data structure in JS with forEach loop

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

In JS I want to transform inputformat into outputformat, I came up with the solution below.

But something went wrong with my logic perhaps the if condition. Console error message says Cannot read property 'date' of undefined yet I have checked out the next item's existence in codition arr[i] && arr[++i] can anybody help me with the problem. Tks a lot~

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

As Xufox stated, i+1 and ++i are not equivalent. In your case forEach is not really appropriate, you might be more interested in 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]
  });
}, {});

or

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM