gpt4 book ai didi

javascript - 重构 JSON 对象数组

转载 作者:行者123 更新时间:2023-12-01 08:29:32 25 4
gpt4 key购买 nike

我有一个 JSON 对象数组。但有些数据是重复的。有没有办法重组数组以排除重复值?我必须使用 map 功能吗?还是 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)

关于javascript - 重构 JSON 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62012273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com