Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map through array merge getting the same for each result [lodash]

I’m trying to merge lessons with user progress data. I believe I have a pointer issue.

I've had success with the inner merge of the two arrays. The issue comes with looping through users and not getting the right lesson data with the progress data attached.

lessons data

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

all users’ progresses

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,
       }
     ],
     ...
   ];

loop through users and merge progresses in lessons

   // 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;
   });

Expected data out of 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”,
       }
     ]
   ]

but getting:

   [
     [
       {
         “id”: “0106c568-70c0-4e56-8139-8e7f7d124f95”,
       },
       {
         “id”: “033e18a2-d470-4fd7-8bdc-53e610f3f784”,
       },
       {
         “id”: “d60f751c-d7d2-4dc6-9eda-a03bc5ebddc6”,
       }
     ]
   ]
like image 941
m_ruby Avatar asked Feb 07 '19 17:02

m_ruby


1 Answers

You could do something like this using a nested .map in 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)
like image 173
adiga Avatar answered Nov 15 '22 14:11

adiga