简体   繁体   English

forEach 对象值等于未定义

[英]forEach objects value equals undefined

Data Received from firebase-realtime-database as followingfirebase-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)将不起作用,因为在收到数据之前产品将是未定义的。
  • Creating a new Array and mapping into it also will not work.创建一个新数组并映射到它也不起作用。

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 undefinednull的情况。

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.

相关问题 DynamoDB 从属性等于值的列表中删除 Map - DynamoDB remove Map from List where property equals value 我如何使用等于当前用户 yearsection 的子 yearsection 的值来调用用户 - how can i call users using the value of the child yearsection that equals the current user yearsection React.js 和 Firebase querySnapshot.forEach 用相同的对象替换数组 - React.js and Firebase querySnapshot.forEach replacing array with identical objects DynamoDB / marshal 函数抱怨未定义的值 - DynamoDB / marshal function complains about an undefined value Firebase 规则 - 如果用户的 uid 等于文档的字段值 userId,则允许读取 - Firebase rules - Allow read if user's uid equals document's field value userId forEach 循环返回值,但我的反应 useState 值只返回一个数组 obj - forEach loop returning the value but my react useState value only returning one array obj 自定义对象的字典,如何最好地使用 List 和 ForEach 在 SwiftUI 视图中排序和显示? - Dictionary of custom objects, how best to sort and display in a SwiftUI view using List and ForEach? 在日志资源管理器中接收“函数返回未定义,预期 Promise 或值”消息 - Receiving "Function returned undefined, expected Promise or value" message in logs explorer 如何更新 Firestore 字段以为其提供空值(未定义或 null)? - How to update a Firestore field to give it an empty value (undefined or null)? 获取对象数组中键值的总和 - Get SUM of value of key inside an array of objects
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM