Not able to show deeply nested JSON Objects to show up.Have been looking at all kinds of stackoverflow posts for this. Appreciate any help on this newbie question. I want it to show details of the athlete JSONObject within the athletes array. It shows up like [Object].
eventUnitResults: [ { is_team: true, athletes: [ [Object], [Object] ] },
{ is_team: true, athletes: [ [Object], [Object] ] } ]
const result = {}
let eventUnitResults = [];
let athletes = [];
for (i=0; i < 2; i++) {
const athlete = {};
athlete.athlete_name = 'Ram' + i;
athlete.athlete_gender = 'M'
athletes.push(athlete);
}
for (j=0;j < 2;j++) {
const nestedResult = {};
nestedResult.is_team = true;
if (athletes) {
nestedResult.athletes = athletes;
}
console.log('nestedResult:', nestedResult);
if (nestedResult) {
eventUnitResults.push(nestedResult);//TODO:
//eventUnitResults.push(JSON.stringify(nestedResult));//TODO:
}
}
console.log('eventUnitResults:', eventUnitResults);//<==== how can I get deeply nested values of athletes showing up properly here
if (eventUnitResults) {
result.event_unit_results = eventUnitResults;
}
console.log('result:', result)
TIA
If you log your objects, you might want to convert the actual object to a string.
If you compare this to java (or most languages):
System.out.println(object);
prints your object.toString()
. Unless you override it, that's the memory address.
In JavaScript:
console.log(object);
[object, object]
would print [object, object]
because it prints WHAT you are printing. In this case, it does not know that you expect a String containing JSON.
Note this does not apply to all browsers. Chrome, for example, wants to help you out and prints the JSON value interactively; you can collapse and uncollapse it.
The solution to this problem, is telling the console explicitly to print a json string. You can do this by calling the build-in json object's function to stringify an object.
JSON.stringify(object);
{ "content": "json" }
For completeness, print the object pretty by setting the print output to 4 spaces indentation:
JSON.stringify(object, null, 4);
prints:
{
"content": "json"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With