0
I have two arrays:
videos = [{
"id": number,
"title": string,
"url": string
}]
watched = [{
"video_id": number
}]
"video_id" is added when a user watches a specific video, this ID is the same as in the videos array.
I need to compare the two arrays, add the "Watched" element based on the following comparison: id === video_id
. For example:
videos = [{
"id": 1,
"title": "one",
"url": "/v1",
"watched": true
}, {
"id": 2,
"title": "two",
"url": "/v2"
"watched": false
}
];
For now I have compared the objects containing the matching Ids as follows:
const watched_video = watched
.filter((x) => x.watched)
.map((x) => x.video_id);
However, I don’t know how to add the watched: true
the element that has matching id’s and watched: false
to those who do not possess.
Edit:
Based on the answers, I was able to solve the problem with the following code:
const watched_video = videos.map((v) => {
if (watched.some((w) => w.video_id === v.id))
return { ...v.dataValues, watched: true };
return { ...v.dataValues, watched: false };
});
I couldn’t understand it. This array
watched
has an object of propertywatched
or not? By your code only"video_id"
.– Cmte Cardeal
You want to add the attribute
watched
in the arrayvideos
on the basis ofid
s that are inwatched
?– Cmte Cardeal
That’s right! I need to add the Watched attribute and make it true for all objects that video.id === Watched.video_id.
– Fred