Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
forEach objects value equals undefined

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.
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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]

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!