我有这个简单的代码来从 api 获取一些对象并将其添加到数组中
const res = await fetch("http://localhost:5000/cart/carts/"+this.state.user);
const data = await res.json();
let data1 = [];
data.forEach(async item => {
const res1 = await fetch("http://localhost:5000/storemanger/products/"+item.product);
const object = await res1.json();
data1.push(object);
});
console.log(data1)
控制台日志输出
但是如果尝试访问第一个元素,例如
console.log(data1[0])
输出“未定义”
我想访问数组内对象的产品名
最佳答案
试试这个,
let data1 = [];
const promiseArray = data.map(item => fetch("http://localhost:5000/storemanger/products/"+item.product))
Promise.all(promiseArray)
.then(result => Promise.all(result.map(v => v.json()))
.then((values) => {
data1 = values
});
关于javascript - 无法从js数组访问对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61969071/