I have a JSON data set that needs to be structured into a 2D array format. The number of columns is determined dynamically after iterating over the JSON, and they are labeled as #1, #2 for multiple occurrences within each item. The expected output should be in the form of a 2D array.
The desired structure of the array is:
[
["firstName", "middleName", "lastName", "addresses: #1 type", "addresses: #1 poBox", "addresses: #1 streetAddress", "addresses: #1 city", "addresses: #1 region", "addresses: #1 postalCode", "addresses: #1 country", "addresses: #2 type", "addresses: #2 poBox", "addresses: #2 streetAddress", "addresses: #2 city", "addresses: #2 region", "addresses: #2 postalCode", "addresses: #3 poBox", "addresses: #3 region", "addresses: #3 postalCode", "addresses: #2 country", "photos: #1 url", "photos: #1 default", "photos: #2 url", "photos: #2 default"],
["John", "Joseph", "Briggs", "home", 111, "", "City1", "", "1ER001", "USA", "work", 222, "", "City2", "Region2", "1ER002", "", "", "", "", "photo.org/person1", "TRUE", "photo.org/person1", "TRUE"],
["Bill", "", "Thatcher", "home", "", "", "City3", "Region3", "1ER003", "USA", "work", 444, "", "", "Region4", "1ER004", 555, "Region5", "1ER005", "", "", "", ""]
]
A visual representation of the expected output can also be viewed here.
Please note that the red header columns do not contain any data and should not be included in the 2D array output. There are approximately 1000 rows with similar data patterns where some entries may be missing fields such as a postal code, middle name, or photos.
You can view an image of the data structure here.
<!DOCTYPE html>
<html>
<body>
<script>
var crowds = [{
"name": [{
"firstName": "John",
"middleName": "Joseph",
"lastName": "Briggs"
}],
"addresses": [{
"type": "home",
"poBox": "111",
"city": "City1",
"postalCode": "1ER001",
"country": "USA"
},
{
"type": "work",
"poBox": "222",
"city": "City2",
"region": "Region2",
"postalCode": "1ER002"
}
],
"photos": [{
"url": "photo.org/person1",
"default": true
},
{
"url": "imagur.org/person1",
"default": true
}
]
},
{
"name": [{
"firstName": "Bill",
"lastName": "Thatcher"
}],
"addresses": [{
"type": "home",
"city": "City3",
"region": "Region3",
"postalCode": "1ER003",
"country": "USA"
},
{
"type": "work",
"poBox": "444",
"region": "Region4",
"postalCode": "1ER004"
}
{
"poBox": "555",
"region": "Region5",
"postalCode": "1ER005"
}
]
}
]
var rows = [];
var headerRow = [];
crowds.forEach(function(crowd) {
var cols = [];
for (key in crowd) {
headerRow.push(key + ":#")
cols.push(crowd[key].firstName)
cols.push(crowd[key].middleName)
cols.push(crowd[key].lastName)
}
rows.push(cols)
})
console.log(JSON.stringify(headerRow.concat(rows)))
</script>
</body>
</html>