I have this Js array:
JavaScript
x
15
15
1
const a = [
2
[
3
"Paris",
4
"75000"
5
],
6
[
7
"Toulouse",
8
"31000"
9
],
10
[
11
"Marseille",
12
"13000"
13
]
14
];
15
How to convert restructure this array to JSON?
JavaScript
1
13
13
1
[{
2
"city": "Paris",
3
"zip": "75000"
4
},
5
{
6
"city": "Toulouse",
7
"zip": "31000"
8
},
9
{
10
"city": "Marseille",
11
"zip": "13000"
12
}]
13
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.
JavaScript
1
26
26
1
const tabs = [
2
[
3
"Paris",
4
"75000"
5
],
6
[
7
"Toulouse",
8
"31000"
9
],
10
[
11
"Marseille",
12
"13000"
13
]
14
];
15
16
// restructure sub-arrays into objects:
17
18
let objectArray = tabs.map(entry=> {
19
const [city, zip] = entry;
20
return {city, zip};
21
})
22
23
// Stringify object array
24
25
let jsonText = JSON.stringify( objectArray, null, 2)
26
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.