[英]forEach objects value equals undefined
Data Received from firebase-realtime-database
as following从
firebase-realtime-database
接收到的数据如下
{
"0": {
"id": 10250903,
...
},
"1": {
"id": 10810490,
...
},
...
}
Code to setProducts
设置产品的
setProducts
const [products, setProducts] = useState();
const {isLoading, setIsLoading} = useData();
useEffect(async () => {
setIsLoading(true);
await firebase
.database()
.ref('events')
.once('value')
.then((events) => {
setProducts(events);
})
.finally(() => setIsLoading(false));
}, []);
I tried to iterate the object to get the values我试图迭代 object 来获取值
products?.forEach((product) => {
console.log(product);
});
Result:结果:
Object {
"id": 10250903,
...
}
Object {
"id": 10810490,
...
}
But when I try to access id
values, console prints undefined但是当我尝试访问
id
值时,控制台打印 undefined
products?.forEach((product) => {
console.log(product.id); // undefined
});
undefined
undefined
I am stuck I tried everything.我被困住了,我尝试了一切。
Object.values(products)
will not work since product will be undefined until data is received. Object.values(products)
将不起作用,因为在收到数据之前产品将是未定义的。You stated that:你说:
Object.values(products) will not work since product will be undefined until data is received.
Object.values(products) 将不起作用,因为在收到数据之前产品将是未定义的。
I think you are very close to the solution.我认为您非常接近解决方案。 Using
products || {}
使用
products || {}
products || {}
handles the case where products
are undefined
or null
. products || {}
处理products
undefined
或null
的情况。
var products = {
"0": {
"id": 10250903,
},
"1": {
"id": 10810490,
},
}
Object.values(products || {}).forEach(p => console.log(p.id))
If you are transforming products into a new products collection, reduce
may become useful:如果您正在将产品转换为新的产品集合,
reduce
可能会变得有用:
Object.values(products || {}).reduce((acc, p) => {
acc[p.id] = p;
return acc;
}, {})
=> =>
{
"10250903": {
"id": 10250903,
...
},
"10810490": {
"id": 10810490,
...
}
}
Or:或者:
Object.values(products || {}).reduce((acc, p) => {
acc.push(p.id)
return acc;
}, [])
=> [10250903, 10810490]
=>
[10250903, 10810490]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.