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

85
Visualizações
Data from the object doesn't convert when using JSON.stringify

I'm stuck in this weird issue that I'm having hard time in understanding what's doing on. When a button is clicked it calls the function onSubmit. What onSubmit function should do is stringify is the object to JSON however for me this doesn't happen. The result I get when I console.log(JSON.stringify(obj)); is [[]]. When I console.log(obj); I can see the object.

I was not able to replicate the same issue in playcode.io and codesandbox.io

  async function onSubmit() {
    let l = [];
    l["Channel"] = undefined;
    l["MetricsData"] = [
      { id: 1, name: "CPA", year: "" },
      { id: 2, name: "Average Gift", year: "" },
      { id: 3, name: "Average Gift Upgrade %", year: "" }
    ];

    let obj = [];
    l.Channel = 1;
    obj.push(l);

    console.log(obj);
    console.log(JSON.stringify(obj)); //[[]]
  
  } 
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

As others have pointed in comments, you're instantiating l as an array and then attempt populating named keys (Channel, Metricsdata).
Note: Technically, arrays are objects, but they're special objects (their keys are intended to be numeric and they also have a few extra props and methods, specific to arrays - e.g: length, pop, push, slice, etc...). Use the link above to read more about arrays.

What you need to do is use l as an object (e.g: {}):

const l = {
  Channel: 1,
  MetricsData: [
    { id: 1, name: "CPA", year: "" },
    { id: 2, name: "Average Gift", year: "" },
    { id: 3, name: "Average Gift Upgrade %", year: "" }
  ]
};

// Uncomment any of the following:

// console.log('object:', l);
// console.log('stringified object:', JSON.stringify(l));

const items = [];
items.push(l);
// console.log('items:', items);
// console.log('first item:', items[0]);

console.log(JSON.stringify(items));

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