I have a JSON response like this:
{
"data":[
{
"type":"node--base_product_coffee",
"id":"6dbb5a52-13ea-4f74-8af9-eb9e3ba45918",
"date":"1990",
"data1":[
{
"type1":"product_coffee1",
"id1":"6dbb5a52-13ea-4f74-8af9-eb9e3ba45777",
" date1 ":[
{
" res ":" oui "
},
{
" res ":" non "
}
]
},
{
"type1":"product_coffee2",
"id1":"6dbb5a52-13ea-4f74-8af9-eb9e3ba45666",
"date1":[
{
" res ":" ouiii "
},
{
" res ":" nonnn "
}
]
}
]
}
]
}
My goal is to able to get value as listfrom dynamic path like data.data1.date1.res to get the result ['oui', 'non', 'ouiii', 'nonnn']
So I started by this function
parseIt = function(response, s) {
if (!response) return null;
if (!s) return obj;
if (Array.isArray(response)) {
var data = JSON.parse(JSON.stringify(response));
} else {
var data = JSON.parse(response);
}
var result = [];
var path = [];
path = s.split('.');
if (Array.isArray(data)) {
for (var i = 0; i < data.length; i++) {
if (getType(data[i][path[0]]) == 'string') {
result.push(data[i][path[0]]);
} else {
parseIt(data[i][path[i]], path.slice(1).join('.'));
}
}
} else {
for (var p in data) {
if (getType(data[p]) == 'string') {
result.push(data[p]);
} else {
parseIt(data[p], path.slice(1).join('.'));
}
}
}
document.writeln('result=>'+result+'</br>');
return result;
}
document.writeln(parseIt(response2, 'data.data1.date1.res')+'</br>');
//Console Output
result=>oui,non
result=>
result=>
result=>
but I face two problems:
- I get Result only for the element of date1.res(which is 'oui' and 'non'), but I need all its elements (which 'oui', 'non', 'ouiii', 'nonnn')
- result is empty (how can store the results in a list when using recursion)
I need your help, because I need this in my work in which we have complex JSON like this.