【发布时间】:2021-07-08 02:08:16
【问题描述】:
我有一个这样的 JSON 响应:
{
"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 "
}
]
}
]
}
]
}
我的目标是能够从像data.data1.date1.res 这样的动态路径中获取值作为列表,以获取结果['oui', 'non', 'ouiii', 'nonnn']
所以我从这个函数开始
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=>
但我面临两个问题:
- 我只得到 date1.res 元素的结果(即 'oui' 和 'non'),但我需要它的所有元素(即 'oui'、'non'、'ouiii'、'nonnn')
- 结果为空(使用递归时如何将结果存储在列表中)
我需要你的帮助,因为我在工作中需要这个,因为我们有像这样的复杂 JSON。
【问题讨论】:
-
为自己节省一些时间 - 使用flat
标签: javascript arrays json object recursion