如何递归地使用jquery追加这个树数据?

时间:2013-03-13 04:46:53

标签: javascript jquery arrays json recursion

[{"tag":35,"value":"W","children":[
    {"tag":55,"value":"GOOG","children":null},
    {"tag":262,"value":"ghost332002m0","children":null},
    {"tag":268,"value":"1","children":[
       {"tag":269,"value":"B","children":null},
       {"tag":271,"value":"0","children":null},
       {"tag":336,"value":"3","children":null}
     ]}
  ]},
   {"tag":35,"value":"W","children":[
       {"tag":55,"value":"GOOG","children":null},
       {"tag":262,"value":"ghost332002m0","children":null},
       {"tag":268,"value":"0","children":null}
   ]} 
]

有JSON,它是FIX市场数据,你有这些嵌套组,所以这是我在JSON中对这些FIX消息的表示。无论如何,我把它发送到我的网络客户端,需要在显示屏中将其展平。

$.getJSON('/receive', function(data, returnValue) {
    $.each(data, function(index,value) {
        $('#output').append('<p>');
        appendStuff(value);
        $('#output').append('</p>');
    });
function appendStuff(children) {
    debug_var.push(children);
    $.each(children, function(child) {
        $('#output').append(child.tag+'='+child.value+' ');
        if (child.children != null) {
            appendStuff(child.children);
        }
    })
}

我正在尝试使用递归来旋转这些数据并将所有内容打印出来。我得到的是:

undefined=undefined undefined=undefined undefined=undefined

我做错了什么?

哦,数据就在debug_var ...

enter image description here

1 个答案:

答案 0 :(得分:3)

你可能想要更接近

的东西
$.getJSON('/receive', function (data) {
    $.each(data, function(index,value) {
        $('#output').append('<p>');
        appendStuff(value.children || []);
        $('#output').append('</p>');
    });
    function appendStuff(children) {
        $.each(children, function(i, child) {
            $('#output').append(child.tag+'='+child.value+' ');
            if (child.children != null) {
                appendStuff(child.children);
            }
        });
    }
});

注意上面没有打印父母的标签,你可能想要添加它。