每个都在每个内 [英] each within each within each

查看:99
本文介绍了每个都在每个内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JSON和getJSON函数等,我正在尝试从JSON中获取数据,这些数据可以包含多个级别并且可以有多个子级。在那一刻,我可以看到我想要的值.each与另一个.each,例如:

I'm new working with JSON and the getJSON function etc and I'm trying to get data from a JSON that goes down several levels and can have multiple children. At the minute I can see the values I want by using .each with another .each such as:

$.each(data, function(i, value1) {
    $.each(value1, function(i, value2) {
        $.each(value2, function(i, value3) {
            $.each(value3, function(i, value4) {
                $.each(value4, function(i, value5) {
                    $.each(value5, function(i, value6) {
                        alert ("we got "+i);
                    });

唯一的问题是,我赢了我总是知道JSON中有什么内容,它可以拥有无​​限的孩子​​。那么我将如何让它变得如此动态?

The only problem is, I won't always know what is in the JSON and it could have unlimited children. So how would I go about making it dynamic as such?

基本上我正在寻找的东西是什么东西继续检查孩子,直到它达到最低水平。

Basically what I'm looking for is something to keep checking for children until it gets to the lowest level.

另外,我知道最后的值是无论价值在哪里的索引JSON,

Also, I know the value i at the very end is the index for whatever value is in the JSON,

有没有办法自动化这个,以便我可以检查比方说,JSON中的'name'会返回'name'的值吗?

Is there any way to automate this also so that I could check for say, 'name' in the JSON and it would return the value of 'name'?

以下是我正在尝试使用的JSON示例:

Here is a sample of the JSON i'm trying to work with:

[
 {
   "children": [
    {
      "children": [
       {
        "children": [
          {
            "children": [
              {
                "bucketPath": "AUDIO\\audio0.mp3",
                "id": 305,
                "modified": "2012-08-02T10:06:52",
                "name": "audio0.mp3",
                "state": "closed"
              }


推荐答案

使用递归:

function recurse(name, obj) {
    if (!obj || typeof obj != "object")
        alert("found leaf '"+name+"': "+obj);
    else
        $.each(obj, recurse);
}
recurse("root", data);






编辑:根据您的JSON,可以制作它更具体:


Based on your JSON, one could make it more specific:

function recurse(arr) {
   for (var i=0; i<arr.length; i++)
       for (var prop in arr[i])
           if (prop == "children") // && arr[i].children instanceof Array
               recurse(arr[i].children);
           else
               alert("we got "+prop+": "+arr[i][prop]);
}
recurse(data);

这篇关于每个都在每个内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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