1

我有以下对象:

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/资源。
使用下划线如何完成此任务的任何想法?谢谢。​</p>

4

5 回答 5

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.

于 2012-08-27T11:33:11.720 回答
1

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/

于 2012-08-27T11:33:20.567 回答
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]);
      }
    }
  }
}
于 2012-08-27T11:57:34.990 回答
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 的奇怪结构(例如,你的名字不能是“孩子”)

于 2012-08-27T11:38:22.503 回答
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)
    }
});
于 2012-08-27T11:39:24.860 回答