如何通过数组合并映射获得相同的每个结果[lodash]

m_r*_*uby 9 javascript arrays lodash

我正在尝试将课程与用户进度数据合并.我相信我有指针问题.

我已经成功完成了两个数组的内部合并.问题在于循环访问用户而没有获得附加进度数据的正确课程数据.

课程数据

   let lessons = [
     {“id”: “0106c568-70c0-4e56-8139-8e7f7d124f95",},
     {“id”: “033e18a2-d470-4fd7-8bdc-53e610f3f784",},
     {“id”: “d60f751c-d7d2-4dc6-9eda-a03bc5ebddc6",},
   ];
Run Code Online (Sandbox Code Playgroud)

所有用户的进步

const usersProgresses = [
     [
       {
         “id”: “cjrtmj9d601b908559oxe8hwk”,
         “lesson”: “0106c568-70c0-4e56-8139-8e7f7d124f95",
         “score”: null,
       },
       {
         “id”: “cjrtmk2hv01bx0855yof2ehj4”,
         “lesson”: “033e18a2-d470-4fd7-8bdc-53e610f3f784”,
         “score”: 100,
       },
       {
         “id”: “cjrtmlohd01cp0855jnzladye”,
         “lesson”: “3724d7df-311c-46d9-934f-a9c44d9335ae”,
         “score”: 20,
       }
     ],
     ...
   ];
Run Code Online (Sandbox Code Playgroud)

循环用户并在课程中合并进度

   // for each user
   const result = usersProgresses.map(user => {
     // merge progress and lesson data by lesson.id
     const mergedProgress = [...lessons].map(lesson => {
       return _.merge(lesson,_ .find(userProgress, { lesson: lesson.id }));
     });
     return mergedProgress;
   });
Run Code Online (Sandbox Code Playgroud)

预期数据来自result:

   [
     [
       {
         “id”: “0106c568-70c0-4e56-8139-8e7f7d124f95”,
         “lesson”: “0106c568-70c0-4e56-8139-8e7f7d124f95”,
         “score”: null,
       },
       {
         “id”: “033e18a2-d470-4fd7-8bdc-53e610f3f784",
         “lesson”: “033e18a2-d470-4fd7-8bdc-53e610f3f784",
         “score”: 100,
       },
       {
         “id”: “d60f751c-d7d2-4dc6-9eda-a03bc5ebddc6”,
       }
     ]
   ]
Run Code Online (Sandbox Code Playgroud)

但得到:

   [
     [
       {
         “id”: “0106c568-70c0-4e56-8139-8e7f7d124f95”,
       },
       {
         “id”: “033e18a2-d470-4fd7-8bdc-53e610f3f784”,
       },
       {
         “id”: “d60f751c-d7d2-4dc6-9eda-a03bc5ebddc6”,
       }
     ]
   ]
Run Code Online (Sandbox Code Playgroud)

adi*_*iga 5

你可以使用嵌套.map在vanilla js中做这样的事情:

const lessons = [{"id":"0106c568-70c0-4e56-8139-8e7f7d124f95",},{"id":"033e18a2-d470-4fd7-8bdc-53e610f3f784",},{"id":"d60f751c-d7d2-4dc6-9eda-a03bc5ebddc6",}]

const usersProgress = [[{"id":"cjrtmj9d601b908559oxe8hwk","lesson":"0106c568-70c0-4e56-8139-8e7f7d124f95","score":null,},{"id":"cjrtmk2hv01bx0855yof2ehj4","lesson":"033e18a2-d470-4fd7-8bdc-53e610f3f784","score":100,},{"id":"cjrtmlohd01cp0855jnzladye","lesson":"3724d7df-311c-46d9-934f-a9c44d9335ae","score":20,}]]

const output = usersProgress.map(user => lessons.map(lesson =>
    ({...user.find(p => p.lesson == lesson.id), ...lesson }))
 );
  
console.log(output)
Run Code Online (Sandbox Code Playgroud)