'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
Solution 1:[1]
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.
Solution 2:[2]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | SteveGreenley |
