问题
I have the following object:
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);
I need to read recursively the xhr
object.
The object I posted is just an example, it means that the children could be more or less.
Anywas objectReader should be able to get the following output:
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."]
I did try to write the following code which it works partially:
_.each(xhr, function (xhrObject, name) {
if(xhrObject.errors) {
console.log(name, xhrObject.errors);
}
});
This is the http://jsfiddle.net/UWEMT/ resource.
Any ideas by using underscore how to accomplish this task? thanks.
回答1:
See this: 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);
})
}
If the object has erros it's an end node, else it's a children containing more objects.
回答2:
It's some strange looking json you have there...
But you can make a recursive loop like this:
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);
http://jsfiddle.net/YE6Qn/1/
回答3:
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);
This code reflects the strange structure of your JSON (e.g., your names cannot be "children")
回答4:
A plain js solution:
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]);
}
}
}
}
回答5:
Just user recursion, jsfidle - 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)
}
});
来源:https://stackoverflow.com/questions/12141059/how-to-read-recursively-an-object-which-looks-like-that