更新:
更新的 fiddle :http://jsfiddle.net/Y2xFV/10/
I accepted one of the below answers although both offered are satisfactory. The one I selected is closer to the direction I myself took. Neither of the offered solutions actually do exactly what I need however.
在实践中,我最终编写了 Angular-js 函数,它可以满足我的实际需求,如下所示..
function getNames(obj) {
if(obj.attrs) {
console.log(obj.attrs.name);
// expressions that utilize key pair values..
}
if(!obj.children) {
return;
}
angular.forEach(obj.children, function(o) {
getNames(o);
});
}
感谢大家的意见和建议。
============================================
我下面有一个 JSON 字符串,我必须获取所有名称的值。我知道有一种递归方法可以做到这一点,但我需要帮助。我在堆栈中搜索了此问题的解决方案,但没有找到任何可以直接解决该问题的内容。
我在工作。我会尽快更新 fiddle 。我的时间非常有限,有时我不会立即回到我的堆栈上。如果这对某人来说是个问题,我深表歉意。然而,我不需要几毫秒的答案,我接受建设性的批评:)。一旦我真正学会了 fiddle ,我就会发布问题。
[
{
"name": "john",
"surname": "doe",
"children": [
{
"name": "anne",
"surname": "peters"
}
]
},
{
"name": "joe",
"surname": "doe",
"children": [
{
"name": "bob",
"surname": "peters",
"children": [
{
"name": "bill",
"surname": "peters"
}
]
}
]
},
{
"name": "jim",
"surname": "doe"
}
]
我需要得到:
约翰 安妮 乔 鲍勃 账单 吉姆
最佳答案
你可以试试这个:
function getNames(obj, list) {
if (!obj) return list;
if (obj instanceof Array) {
for (var i in obj) {
list = list.concat(getNames(obj[i], []));
}
return list;
}
if (obj.name) list.push(obj.name);
if (obj.children) return getNames(obj.children, list);
return list;
}
// Outputs a list of names
console.log(getNames(JSON.parse(json), []));
关于javascript - 递归搜索 JSON 字符串字典,查找键值对在 "name"中的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20913403/