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

163
Visualizações
Creating a nested Json from an array

I have this Js array:

const a = [
  [
    "Paris",
    "75000"
  ],
  [
    "Toulouse",
    "31000"
  ],
  [
    "Marseille",
    "13000"
  ]
];

How to convert restructure this array to JSON?

[{
  "city": "Paris",
  "zip": "75000"
},
{
  "city": "Toulouse",
  "zip": "31000"
},
{
  "city": "Marseille",
  "zip": "13000"
}]

I tried with the JSON.stringify() function but I don't get the expected result.

Thanks

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

0

Youre array declaration isn't correct. This is the correct syntax for declaring an array in JS and using JSON.stringify on it:

tab = [
  {city: 'Paris', zip: '75000'},
  {city: 'Toulouse', zip: '31000'},
  {city: 'Marseille', zip: '13000'}
];

JSON.stringify(tab, null, 2)
about 4 years ago · Juan Pablo Isaza Relatório

0

You could use Array.prototype.map to convert sub-array entries of the original array into objects with suitably named properties, and call JSON.stringify on the result.

const tabs = [
  [
    "Paris",
    "75000"
  ],
  [
    "Toulouse",
    "31000"
  ],
  [
    "Marseille",
    "13000"
  ]
];

// restructure sub-arrays into objects:

let objectArray = tabs.map(entry=> {
    const [city, zip] = entry;
    return {city, zip};
})

// Stringify object array

let jsonText = JSON.stringify( objectArray, null, 2)
console.log(jsonText);  

The map function is using Destructuring assignment to extract city and zip values from each sub-array.

A null second and numeric third parameter supplied to JSON.stringify improve human readability of the output but are generally omitted in production environments to reduce the length of network messages.

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