我有以下对象:
var xhr = JSON.parse('{"name1":{"errors":["This value should not be blank."]}, "children":{"name2":{"errors":["This value should not be blank."]},"message":[],"name3":{"errors":["This value should not be blank."]}, "children":{"name4":{"errors":["This value should not be blank."]} }}}');
console.log(xhr);
我需要递归读取xhr
对象
我发布的对象只是一个例子,这意味着孩子可能或多或少
Anywas objectReader应该能够获得以下输出:
name1 ["This value should not be blank."]
name2 ["This value should not be blank."]
name3 ["This value should not be blank."]
name4 ["This value should not be blank."]
我确实尝试编写以下代码部分工作:
_.each(xhr, function (xhrObject, name) {
if(xhrObject.errors) {
console.log(name, xhrObject.errors);
}
});
这是http://jsfiddle.net/UWEMT/资源 通过使用下划线如何完成此任务的任何想法?谢谢。
答案 0 :(得分:1)
请参阅:http://jsfiddle.net/UWEMT/6/
prs(xhr);
function prs(x){
_.each(x, function (xhrObject, name) {
if(xhrObject.errors) {
console.log(name, xhrObject.errors);
}
else prs(xhrObject);
})
}
如果对象有错误,那么它就是一个结束节点,否则就是包含更多对象的子节点。
答案 1 :(得分:1)
你有一些看起来很奇怪的json ......
但你可以像这样做一个递归循环:
var xhr = JSON.parse('{"name1":{"errors":["This value should not be blank."]}, "children":{"name2":{"errors":["This value should not be blank."]},"message":[],"name3":{"errors":["This value should not be blank."]}, "children":{"name4":{"errors":["This value should not be blank."]} }}}');
function loop( json ) {
_.each(json, function (value, key) {
if(value.errors) {
console.log(key, value.errors);
}
else {
loop(value);
}
});
}
loop(xhr);
答案 2 :(得分:0)
var xhr = JSON.parse("…");
(function recurse(obj) {
for (var name in obj) {
if (name != "children")
console.log(name, obj[name].errors);
}
if ("children" in obj)
recurse(obj.children);
})(xhr);
此代码反映了JSON的奇怪结构(例如,您的名字不能是“儿童”)
答案 3 :(得分:0)
只是用户递归,jsfiddle - http://jsfiddle.net/UWEMT/7/
_.each(xhr, function read(item, name) {
if(name == "children") {
_.each(item, read);
}
if (item.errors) {
console.log(name, item.errors)
}
});
答案 4 :(得分:0)
普通的js解决方案:
function convertObj(obj) {
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
if (obj[p].errors) {
console.log(p, obj[p].errors);
} else {
convertObj(obj[p]);
}
}
}
}