gpt4 book ai didi

javascript - 创建嵌套对象数组 Javascript

转载 作者:行者123 更新时间:2023-12-03 07:24:28 26 4
gpt4 key购买 nike

我在下面的 json 中有一个类(class)列表。我试图获得所需的输出来制作我想要的数组,但我在制作新数组时遇到了问题。

我尝试使用下面的代码片段获取它,但在使用 [courses[i].client_id]结果 时显示错误。

let courses = [
{course_id: 1, name: "Test1", description: "Test1 desc", video_url: "111", client_id: 1},
{course_id: 3, name: "A new course", description: "This is a temporary description used to test functionality. ", video_url: "https://vimeo.com/", client_id: 1},
{course_id: 5, name: "Teaching", description: "programming language", video_url: "https://vimeo.com", client_id: 1},
{course_id: 13, name: "Course285", description: "desc285", video_url: "", client_id: 2},
{course_id: 16, name: "The NEW", description: "The Course is an training", video_url: "https://vimeo.com/", client_id: 1}
]

let result = [];

for (let i = 0; i < courses.length; i++) {
if (courses && courses.length) {
result[i][courses[i].client_id] = {
clientId: courses[i].client_id
} ;
}
}

预期输出

[
{client_id: 1, courses:[{
course_id:1,
course_name: Test1,
course_desc: description
},{
course_id:2,
course_name: Test1,
course_desc: description
}]},
{client_id:2,courses[{
....
}]}
]

最佳答案

我的减少案例:

const userCourses = courses.reduce((acc, rec) => {
const user = acc.find(a=>a.client_id === rec.client_id)
if (user) {
user.courses = [...user.courses, {course_id:rec.course_id, course_name: rec.name, course_desc: rec.description}]
return [...acc]
}
return [...acc, { client_id: rec.client_id, courses: [{course_id: rec.course_id, course_name: rec.name, course_desc: rec.description}] }]
}, [])

在 Playground 上查看:https://jscomplete.com/playground/s538993

关于javascript - 创建嵌套对象数组 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63011721/

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