Skip to content
Advertisement

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement