在某个项目中,我有两个对象obj1和obj2。
obj1 (Items Data)如下:
obj1 = [
{"_id": "abscdfg1234","blur_photo": [{"potrait": "https://img.jpg"}]}, <-- Images here are blur
{"_id": "pqrst54678","blur_photo": [{"potrait": "https://img2.jpg"}]},
{"_id": "uioyt12321","blur_photo": [{"potrait": "https://img3.jpg"}]},
{"_id": "rtye33452","blur_photo": [{"potrait": "https://img4.jpg"}]},
]
obj2 (Purchase Data)如下:
obj2 = [
{"_id": "pqrst54678", "photo": [{"cover":"https://newimg2.jpg"}]} <-- Images here are normal
]
我所做的是:
{
obj1.map((data) => (
<img src={(obj2.some(purchaseItem => purchaseItem._id === data._id)) ? (obj2.filter(purchaseItem => purchaseItem._id === data._id)) : data.blur_photo.potrait} height="100%" width="100%" />
))
}
当映射obj1的id与obj2的id时,我如何从obj2对象获得图像数据?
你找不到这些JS内联的幼崽,我一点也不惊讶。
您可以使用Array.find
实际获得匹配的元素。Array.some
返回一个Boolean
然后就是用正确的路径访问数据的问题了。你犯了一个错误:blur_photo
持有一组肖像。
const getSrc = itemData => {
const matchingId = item => item._id === itemData._id;
const match = purchaseData.find(matchingId);
return match
? match.photo[0].cover
: itemData.blur_photo[0].potrait
};
const srcs = itemsData.map(getSrc);
{
srcs.map(src => (
<img src={src} height="100%" width="100%" />
))
}