javascript - 用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
}
})
解决方案
正如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;
}, {});
推荐阅读
- c - 如何让'isalpha'遍历字符串的每个字符?
- python - 向 AWS EC2 实例上托管的服务器发送 HTTP 请求
- python - 如何使用 videoflow 从视频 url 或 USB 摄像头读取?
- python - Python 3.x/json 包无法将此 json 字符串转换为列表
- nginx - NGINX:执行反向代理时如何删除端口?
- node.js - 如何测试通过 express 模拟调用的路由处理程序
- yocto - Yocto 修改源代码后重建镜像
- asp.net-mvc - 如何在 Asp.Net MVC 的 ActionResult 方法中设置可选参数值?
- javascript - 重新加载页面wordpress后登录
- scala - 如何成功地结合流畅的阅读动作和流畅的写入动作以进行理解