我有两个对象数组。我想匹配订单 id 和图像 item_id 并在表列中显示订单图像。我尝试了 forEach 和 setState 与图像文件名,但它只给了我一张图片。有没有其他方法可以实现这一点。我在 React 中使用基于函数的组件。谢谢// orders array of objectlet orders = [ {id: 1, heading: "ddd", description: "ddd", user_created: "Joe"}, {id: 2, heading: "eee", description: "eee", user_created: "Mike"}]// images array of objectlet images = [ {item_id: 1, filename: "nat-2-large.jpg"}, {item_id: 2, filename: "nat-3-large.jpg"},]// comparisonconst [filenameForPath, setFilenameForPath] = useState('');const getFilePath = () => { ordersArr.forEach(order => { files.forEach((file) => { if(order.id == file.item_id){ console.log("success"); setFilenameForPath(file.filename); } }); });}useEffect(() => { getFilePath();},[]);
2 回答
互换的青春
TA贡献1797条经验 获得超6个赞
在这里,底部的变量映射是您的结果。
let orders = [
{id: 1, heading: "ddd", description: "ddd", user_created: "Joe"},
{id: 2, heading: "eee", description: "eee", user_created: "Mike"}
]
// images array of object
let images = [
{item_id: 1, filename: "nat-2-large.jpg"},
{item_id: 2, filename: "nat-3-large.jpg"},
]
const mapped = orders.reduce((arr, item, index)=> {
let res;
images.forEach((file) => {
if(file.item_id === item.id) {
res = {...item, ...file};
}
})
return [...arr, res]
}, [])
console.log(mapped)
拉风的咖菲猫
TA贡献1995条经验 获得超2个赞
如果您确定两个项目的数量相等并且 id 是唯一的,您可以执行类似的操作
let result = orders.map((order,index) => order.id === images[index].item_id ? images[index] : null)
添加回答
举报
0/150
提交
取消