const groups = [
{
name: "1",
subjects: [1, 2]
},
{
name: "2",
subjects: [1]
},
]
const subjects = [
{
id: 1,
name: "English",
},
{
id: 2,
name: "Mathematics",
},
{
id: 3,
name: "Physics",
},
]
example:[
{
name: "1",
subjects: [
{
id: 1,
name: "English",
},
{
id: 2,
name: "Mathematics",
},
]
const groupsSubject = groups.map(group => {
return {
...group,
subjects: subjects.id
}
})
You can create an object lookup of subjects based on the id. Then iterate through your group and assign the respective subjects.
const groups = [ { name: "1", subjects: [1, 2] }, { name: "2", subjects: [1] }],
subjects = [ { id: 1, name: "English", }, { id: 2, name: "Mathematics", }, { id: 3, name: "Physics", }, ],
lookup = Object.fromEntries(subjects.map(o => [o.id, o])),
result = groups.map(({name, subjects}) => ({name, subjects: subjects.map(id => ({...lookup[id]}))}));
console.log(result);
.as-console-wrapper { min-height: 100%!important; top: 0; }
This is my answer:
const groups = [
{
name: '1',
subjects: [ 1, 2 ]
},
{
name: '2',
subjects: [ 1 ]
}
]
const subjects = [
{
id: 1,
name: 'English'
},
{
id: 2,
name: 'Mathematics'
},
{
id: 3,
name: 'Physics'
}
]
const group = (groups, subjects) => {
return groups.map((group) => ({
name: group.name,
subjects: subjects.filter((subject) => group.subjects.includes(subject.id))
}))
}
console.log(group(groups, subjects))
Output:
[
{ name: '1', subjects: [ [Object], [Object] ] },
{ name: '2', subjects: [ [Object] ] }
]
Map and Array#map, create a map where the subject id is the key and the subject is the valueArray#map, iterate over the groups array. In each iteration, the subjects list will be created using Array#map and Map#get to transform ids to objectsconst _getGroupWithSubjectDetails = (groups = [], subjects = []) => {
const subjectMap = new Map(
subjects.map(subject => ([subject.id, subject]))
);
return groups.map(({ subjects = [], ...group }) => ({
...group,
subjects: subjects.map(subjectId => ({ ...(subjectMap.get(subjectId) || {}) }))
}));
}
const
groups = [ { name: "1", subjects: [1, 2] }, { name: "2", subjects: [1] } ],
subjects = [ { id: 1, name: "English" }, { id: 2, name: "Mathematics" }, { id: 3, name: "Physics" } ];
console.log( _getGroupWithSubjectDetails(groups, subjects) );