I am trying to traverse json object to get value of a key from it and was able to do that.
This is the code which i have tried :
var json = {
"SERVICE": {
"Support1": {
"MODULE": {
"Something": {
"SUBMODULE": {
"Abc": {
"PRODUCT": [{
"productName": "something1",
}]
}
}
}
}
},
"Support2": {
"MODULE": {
"Something2": {
"SUBMODULE": {
"Abc2": {
"PRODUCT": [{
"productName": "something10",
}]
}
}
}
}
}
},
}
Object.keys(json.SERVICE).forEach(service => {
var module = Object.keys(json.SERVICE[service].MODULE);
module.forEach(modules => {
var sub_module = Object.keys(json.SERVICE[service].MODULE[modules].SUBMODULE);
sub_module.forEach(products => {
var products = json.SERVICE[service].MODULE[modules].SUBMODULE[products].PRODUCT;
products.forEach(value => {
console.log(value.productName)
})
})
})
})
Is there any other way to traverse this dynamic json because multiple forEach doesn’t seems proper or can i get the "PRODUCT" key values directly without traversing ?
Thank you for helping .
4
Answers
A recursive function can be used here instead.
You can use recursion
Just create recursive function like code below to solve that problem:
Javascript already has a built-in json walker:
JSON.strinfigy
: