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中,我想将输入格式转换为输出格式,我提出了以下解决方案。
但是我的逻辑可能出了问题,如果条件成立。控制台错误消息说无法读取未定义的属性“日期”,但是我已经检查了下一个项目的存在,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
}
})
作为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;
}, {});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句