Reputation: 677
I need to extract json and print it. At first I did manually but that's obviously not the right way. When I try to use forEach loop looped through got 3 object not sure what to do next. My question is is it possible to display data using only loops?
jsonDisplay = () => {
let data = `{
"name": "GI",
"size": 10,
"nodes": [
{
"name": "Mysterious",
"size": 2,
"nodes": [
{
"name": "Center",
"size": 1,
"nodes": [
{
"name": "Fisherman",
"size": 0.5,
"nodes": []
}
]
},
{
"name": "Dog",
"size": 1,
"nodes": []
}
]
},
{
"name": "Cat",
"size": 4,
"nodes": []
}
]
}
`
let json = JSON.parse(data);
let display = document.getElementById('json');
let display2 = document.getElementById('jsonloop');
console.log(json);
json.nodes.forEach(function(element) {
console.log(element);
});
display.innerHTML = `${json.name} ${json.size}
<br>
${json.name} - ${json.nodes[0].name} ${json.nodes[0].size}
<br>
${json.name} - ${json.nodes[0].name} - ${json.nodes[0].nodes[0].name} ${json.nodes[0].nodes[0].size}
<br>
${json.name} - ${json.nodes[0].name} - ${json.nodes[0].nodes[0].name} ${json.nodes[0].nodes[0].nodes[0].name} - ${json.nodes[0].nodes[0].nodes[0].size}
<br>
${json.name} - ${json.nodes[0].name} - ${json.nodes[0].nodes[1].name} - ${json.nodes[0].nodes[1].size}
<br>
${json.name} - ${json.nodes[1].name} - ${json.nodes[1].size}`;
}
jsonDisplay();
Upvotes: 0
Views: 48
Reputation: 63524
So you want to print out the name/size of each nested object? Here's a basic recursive function that will help.
const data = {"name":"GI","size":10,"nodes":[{"name":"Mysterious","size":2,"nodes":[{"name":"Center","size":1,"nodes":[{"name":"Fisherman","size":0.5,"nodes":[]}]},{"name":"Dog","size":1,"nodes":[]}]},{"name":"Cat","size":4,"nodes":[]}]};
(function recursivePrint({ name, size, nodes }) {
console.log(name, size);
nodes.length && nodes.forEach(node => recursivePrint(node));
})(data);
Upvotes: 1