Home > database >  forEach objects value equals undefined
forEach objects value equals undefined

Time:05-23

Data Received from firebase-realtime-database as following

{
  "0": {
    "id": 10250903,
    ...
  },
  "1": {
    "id": 10810490,
    ...
  },
    ...
}

Code to 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

products?.forEach((product) => {
              console.log(product);
});

Result:

Object {
  "id": 10250903,
  ...
}
Object {
  "id": 10810490,
  ...
}

But when I try to access id values, console prints 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.
  • Creating a new Array and mapping into it also will not work.

CodePudding user response:

You stated that:

Object.values(products) will not work since product will be undefined until data is received.

I think you are very close to the solution. Using products || {} handles the case where products are undefined or 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:

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]

  • Related