Issue
I have two arrays:
workers: [
{name: Jonh, id: 1},
{name: Mixel, id: 2},
{name: Carl, id: 3}
]
diseases: [
{diseaseID: 50, name: Jonh, diseaseName: Cancer},
{diseaseID: 60, name: Jonh, diseaseName: Lupus },
{diseaseID: 70, name: Carl, diseaseName: BrainShok}
]
and what i need is making a new a array mergin some elements of the both array, when the names are the same, for example:
workers.forEach(data => {
this.theNewArray.push({
"newName" = data.name
"newID"= data.diseaseID
"newdiseaseID" = "??????????????(here is the problem, idk how to make a push of the disease everytime when the name are the same)
})
})
And in the very end, when the forEach end, the array should be something like this:
this.theNewArray = [
{ "NewName": "Jonh", "newID": "1", "newdiseaseID" = [
{"diseaseID": '50', "diseaseName": 'Cancer'},
{"diseaseID": '60', "diseaseName": 'Lupus '}
]},
{ "NewName": "Mixel", "newID": "2", "newdiseaseID" = []},
{ "NewName": "Carl", "newID": "3", "newdiseaseID" = [{"diseaseID": '70', "diseaseName": 'BrainShok'}]}
]
How can i do this? please help
Solution
You can do this using map and filter. No need for looping.
const workers = [
{name: 'Jonh', id: 1},
{name: 'Mixel', id: 2},
{name: 'Carl', id: 3}
];
const diseases = [
{diseaseID: 50, name: 'Jonh', diseaseName: 'Cancer'},
{diseaseID: 60, name: 'Jonh', diseaseName: 'Lupus'},
{diseaseID: 70, name: 'Carl', diseaseName: 'BrainShok'}
];
const newArray = workers.map((worker) => (
{
newName: worker.name,
newId: worker.id,
newDiseaseId: diseases.filter(disease => disease.name === worker.name).map(({ diseaseID, diseaseName }) => ({ diseaseID, diseaseName }))
}
));
console.log(newArray);
Answered By - Nikki9696
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.