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

161
Views
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 answers
Answer question

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 Report

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 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!