Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda