Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
JAVASCRIPT STORAGE / CHAPTER 06 / Learn / LESSON 03
Theory. Real data is nested: an array of records, and each record has an array of parts. JSON carries it without trouble — stringify walks the depth itself. After parse you get the same structure back.
The work is in the walk: for (const item of data) for the outer array, and inside a second loop (or reduce) for the parts. Show the result as list items (createElement + appendChild) and a count.
Small examples:
const data = JSON.parse(raw.textContent); for (const item of data) { let sum = 0; for (const part of item.parts) sum += part.v; const li = document.createElement("li"); li.textContent = item.name + ": " + sum; list.appendChild(li); } count.textContent = String(data.length);
JSON.stringify(data[0]) shows only the first record with all its nesting.
Common mistake: forgetting that parts is an array; adding strings instead of numbers; not resetting the sum for each record.
<pre id="raw">[{"id":1,"name":"Rent","parts":[{"k":"base","v":400},{"k":"fees","v":100}]},{"id":2,"name":"Food","parts":[{"k":"market","v":150}]}]</pre><ul id="list"></ul><p id="count"></p><p id="first"></p>Nested JSON is walked with a loop in a loop; stringify returns the whole first record.
(empty)Press Run — HTML loads in a sandbox iframe; Stop removes the iframe (also kills infinite loops).
›