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

246
Visualizações
TypeError: Cannot read properties of undefined (reading 'product-1')

So I am trying to display JSON data in my React.js project, but I am getting an error that I can't figure out. I've spent 2 days trying to figure it out, but had no luck

The JSON data: (filename: products.json)

{
    "product-1": [
        {
            "id": 1,
            "name": "product-1",
        }
    ],

    "product-2": [
        {
            "id": 2,
            "name": "product-2",
        }
    ],

    "product-3": [
        {
            "id": 3,
            "name": "product-3",
        }
    ]
}

My javascript:

  const productsData = Object.keys(backendData).map(key => {
    return {
        [key]: backendData[key]
    }
  })

  console.log(productsData[0].products["product-1"][0].id)

error: enter image description here

Log of backEndData: enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Because productsData will return you array like this:

    [ 
        { "product-1": [
            {
                "id": 1,
                "name": "product-1",
            }
        ]}, 
        {"product-2": [
            {
                "id": 2,
                "name": "product-2",
            }
        ]}, .... 
    ]

Meaning this is array of objects, where each object have one key-value pair, where key is name and value is an array. If you want to access id then you should do like this:

productsData[0]["product-1"][0].id

UPDATED AFTER UPDATE OF OP

Since your backendData value does not match product.json, I will ignore that product.json and write you the solution which will work for the value of backendData you just provided.

const productsData = backendData.products;
const id = productsData[0]["product-1"][0].id;
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