i have the following array
response=[
{
"mId": "4a993417-3dae-4a85-bb2e-c535d7fda6d7",
"title": "test2",
"score": "4",
"id": "91ce873f-6e58-4c30-86d4-4eb7f200640e"
}
]
[
{
"mId": "7896548-3dae-4a85-bb2e-c855d7fda6d7",
"title": "discussion",
"score": "18",
"id": "91ce873f-6e58-4c30-86d4-4eb7f200640e"
}
]
[
{
"mId": "20d78952-3dae-4a85-bb2e-c535d7fda6d7",
"title": "test",
"score": "1",
"id": "7777777f-6e58-4c30-86d4-4eb7f200640e"
}
]
i then have another array that looks as follows
mixture=[{"id":"4a993417-3dae-4a85-bb2e-c535d7fda6d7","name":"flour","description":"10g sold"}]
[{"id":"20d78952-3dae-4a85-bb2e-c535d7fda6d7","name":"teabag","description":"stock arriving"}]
how do i check the mId from the response array onto the corresponding array from mixture to get back the name so my new array should look as follows
newArray=[{
"name":"flour"
"mId": "4a993417-3dae-4a85-bb2e-c535d7fda6d7",
"title": "test2",
"score": "4",
"id": "91ce873f-6e58-4c30-86d4-4eb7f200640e"
}]
[{ "name":"flour"
"mId": "4a993417-3dae-4a85-bb2e-c535d7fda6d7",
"title": "discussion",
"score": "18",
"id": "91ce873f-6e58-4c30-86d4-4eb7f200640e"
}]
[{ "name":"testbag"
"mId": "7896548-3dae-4a85-bb2e-c855d7fda6d7",
"title": "test",
"score": "1",
"id": "7777777f-6e58-4c30-86d4-4eb7f200640e"
}]
As long as you write your response and mixture arrays correctly, you can achieve it by using a combination of Array.prototype.map() and Array.prototype.find()
const newArray = response.map(item => {
const mix = mixture.find(mix => mix.id === item.mId);
if (mix) {
item.name = mix.name;
}
return item;
})