I have the following JSON with "section" objects containing other "section" objects and "items". From this object, i need to extract the "items" field name (concatenation of all the parent sections and its name attribute") and its value. What is the efficient way to do this?
Please note, the following is just a part of my json. Nesting levels of sections and items are unlimited. I need to do something recursively.
JSON:
{
"section": [
{
"fieldId": "t1",
"name": "section-1",
"section": [
{
"fieldId": "t-1",
"name": "section2",
"and": [
{
"fieldId": null,
"items": [
{
"fieldId": "c-2",
"name": "item1",
"value": "123"
},
{
"fieldId": "c-3",
"name": "item2",
"value": "dsadsaddsa"
}
]
}
],
"section": []
}
]
}
]
}
Javascript I started writing (not complete, I am stuck):
function process(key,value) {
if (key == "section")
console.log(key + " : " + JSON.stringify(value[0]));
}
function traverse(o,func) {
for (var i in o) {
func.apply(this,[i,o[i]]);
if (typeof(o[i])=="object") {
traverse(o[i],func);
}
}
}
Expected output: A javascript object
{"section1-section2-item1":123, "section1-section2-item2":"dsadsaddsa"}
sectionanditems? The latter would be much more efficient.traversefunction yourself, if seems quite abstract? How do you call it?andproperty (in your example) can be ignored?