慕俠2389804
2023-09-07 16:49:06
我有兩個對象數組。我想匹配訂單 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
提交
取消