我有一个JSON对象数组。但是,某些数据是重复的。有没有办法重组数组以排除重复的值?我必须使用地图功能吗?还是for循环?
userData = [{id:'101', Time:'3:00pm', Date:'5/25/20'},
{id:'101', Time:'5:00pm', Date:'5/25/20'},
{id:'101', Time:'5:00pm', Date:'6/25/20'},
{id:'105', Time:'1:00pm', Date:'3/25/20'},
{id:'105', Time:'5:00pm', Date:'5/25/20'}
]
是否可以像这样重组数据?
userData = [ {id:'101', Time:['3:00pm','5:00pm'], Date:['5/25/20', '6/25/20']},
{id:'105', Time:['1:00pm','5:00pm'], Date:['3/25/20','5/25/20']}
]
如果您有任何指导或指示,将不胜感激!
谢谢!
最佳答案
let userData = [{id:'101', Time:'3:00pm', Date:'5/25/20'},
{id:'101', Time:'5:00pm', Date:'5/25/20'},
{id:'101', Time:'5:00pm', Date:'6/25/20'},
{id:'105', Time:'1:00pm', Date:'3/25/20'},
{id:'105', Time:'5:00pm', Date:'5/25/20'}
]
let formattedUserData = {}
userData.forEach(user=>{
if(!formattedUserData[user.id]) formattedUserData[user.id]= {
id: user.id,
Time: [],
Date: [],
}
formattedUserData[user.id].Time.push(user.Time)
formattedUserData[user.id].Date.push(user.Date)
})
const finalResponse = Object.entries(formattedUserData).map((e) => ( { ...e[1] } ));
console.log("finalResponse",finalResponse)