iterate nested json object javascript code example
Example 1: iterate through nested object javascript
function nestedLoop(obj) {
const res = {};
function recurse(obj, current) {
for (const key in obj) {
let value = obj[key];
if(value != undefined) {
if (value && typeof value === 'object') {
recurse(value, key);
} else {
res[key] = value;
}
}
}
}
recurse(obj);
return res;
}
Example 2: loop through nested json object typescript
var catalog =
{
"products": [
{
"name": "prod 1",
"versions": [
"ver 1",
"ver 2"
]
},
{
"name": "prod 2",
"versions": [
"ver 1",
"ver 2"
]
}
]
};
for(var i = 0; i < catalog.products.length; i++)
{
var product = catalog.products[i];
var productName = product.name;
for(var j = 0; j < product.versions.length; j++)
{
var version = product.versions[j];
}
}