javascript - merge, combine, transform 2 different arrays of Objects

前端 未结 3 379
清歌不尽
清歌不尽 2021-01-25 03:16

I can\'t figure it out how to transform and combine 2 arrays of object.

I have this 2 arrays of objects:

const selectedCourse = [
    {
      \"courseTyp         


        
3条回答
  •  生来不讨喜
    2021-01-25 03:36

    Assuming, you want all items with selectedCourse, you could take a Map and collect all courses and later greate a new array out of the found values.

    This solution includes Fish as well.

    const
        selectedCourse = [{ courseType: [5], id: 26, title: "Apple Tart with Apricot Glaze" }, { courseType: [3], id: 16, title: "Classic Caesar Salad" }, { courseType: [1, 2], id: 10, title: "Lobster Bisque" }, { courseType: [3], id: 16, title: "Classic Caesar Salad" }],
        courseTypes = [{ name: "Hors d'oeuvres", id: 0 }, { name: "Soup", id: 1 }, { name: "Fish", id: 2 }, { name: "Salad", id: 3 }, { name: "Main course", id: 4 }, { name: "Dessert", id: 5 }],
        map = selectedCourse.reduce((m, o) => o.courseType.reduce((n, id) => n.set(id, [...(n.get(id) || []), o]), m), new Map),
        result = courseTypes.reduce(
            (r, { name: courseName, id: courseType }) => (map.get(courseType) || []).reduce((s, courses) => s.concat({ courseType, courseName, courses }), r),
            []
        );
       
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题