我有以下数组
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"
}
]
然后我有另一个数组,看起来像下面的
mixture=[{"id":"4a993417-3dae-4a85-bb2e-c535d7fda6d7","name":"flour","description":"10g sold"}]
[{"id":"20d78952-3dae-4a85-bb2e-c535d7fda6d7","name":"teabag","description":"stock arriving"}]
我如何检查mId从响应数组到相应的数组从混合物得到回的名称所以我的新数组应该如下所示
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"
}]
只要正确编写响应数组和混合数组,就可以通过使用Array.prototype.map()和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;
})