如何递归读取看起来像这样的对象 [英] How to read recursively an object which looks like that

查看:45
本文介绍了如何递归读取看起来像这样的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下对象:

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 应该能够获得以下输出:

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);
    }
});

这是http://jsfiddle.net/UWEMT/ 资源.
使用下划线如何完成此任务的任何想法?谢谢.

This is the http://jsfiddle.net/UWEMT/ resource.
Any ideas by using underscore how to accomplish this task? thanks. ​

推荐答案

你的 json 看起来很奇怪...

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/

这篇关于如何递归读取看起来像这样的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆