Is there a way to extract values from a deeply nested JSON array?
I'm looking to retrieve all pairs of (nameValue and value) from the JSON provided below
var json = [{
name: 'Firstgroup',
elements: [{
name: 'Field1',
elements: [{
name: 'country32',
elements: [{
nameValue: 'city1',
value: 2025
}]
}]
},
{
name: 'Field2',
elements: [{
name: 'country22',
elements: [{
nameValue: 'city2',
value: 1875
}]
},
{
name: 'country12',
elements: [{
nameValue: 'city3',
value: 1810
}]
}]
}]
},
{
name: 'Secondgroup',
elements: [{
name: 'Field1',
elements: [{
name: 'country52',
elements: [{
nameValue: 'city4',
value: 1310
},
{
nameValue: 'city5',
value: 1125
}]
}]
},
{
name: 'Field3',
elements: [{
name: 'country42',
elements: [{
nameValue: 'city6',
value: 1100
}]
}]
}]
}];
I have successfully extracted the first pair using the code snippet below
function getDataProvider(array)
{
var dataPoint = [];
var elements = 'elements';
var name = 'nameValue';
var value = 'value';
var i, j, len;
for (j = 0; j < array.length; j++) {
i = array[j];
if (i[elements]) {
this.getDataProvider(i[elements]);
} else {
dataPoint.push({
name: i[name],
value: i[value]
});
}
}
return dataPoint;
}
How can I extract all pairs from the above JSON considering that the depth is variable and unknown, but will always include (nameValue and value) pairs?