I have an array of objects like this
const data = [{
"id": 1,
"content": {
"type": "img",
"state": "rejected"
},
"entity": {
"type": "student",
"studentID": [
44
]
},
"status": "rejected"
},
{
"id": 2,
"content": {
"type": "img",
"state": "approved"
},
"entity": {
"type": "student",
"studentID": [
45
]
},
"status": "approved"
},
{
"id": 3,
"content": {
"type": "img",
"state": "approved"
},
"entity": {
"type": "student",
"studentID": [
44
]
},
"status": "approved"
}
]
As you can see, we have 2 objects of student id 44 (one with status rejected and one with approved) and one of student id 45. I have another array of object with student info like this
const students = [{
student_id: 44,
fname: 'student 1',
lname: '.',
school: 'XYZ',
},
{
student_id: 45,
fname: 'student 2',
lname: '.',
school: 'ABC',
}
]
Now, i want to create a new array of object with both of them mapped, but each object in data mapped with their corresponding student (relation between entity.studentID[0] in data with student_id in students, so that the resultant array of object is
[{
student_id: 44,
fname: 'student 1',
lname: '.',
school: 'XYZ',
item: {
id: 1,
status: "rejected"
},
},
{
student_id: 45,
fname: 'student 2',
lname: '.',
school: 'ABC',
item: {
id: 2,
status: "approved"
},
},
{
student_id: 44,
fname: 'student 1',
lname: '.',
school: 'XYZ',
item: {
id: 3,
status: "approved"
},
},
]
What i did was i ran a loop on students and tried using map but that returns me an array of objects that qualify the condition instead of the objects themselves.
let arr = []
for (let student of students) {
let obj = { ...student
};
obj["item"] = data.map((p) => {
if (p.entity.studentId[0] === student.student_id) {
return {
id: p.id,
status: p.status,
};
}
});
arr.push(obj);
}
Where am i going wrong and what should i do instead?
mapreturns an Array, so ifitemis supposed to be a plain Object, why are you setting it to the result ofdata.map(…)? Your entire resulting object (and not theitemproperty) looks like a mapping fromdata, perhaps followed by a filtering usingstudents.dataand determine which object matches its correspondingstudent. I know i should not return the map but then how should i return the object?