如何显示JSON对象的ID和子项?

时间:2015-07-30 12:37:09

标签: javascript jquery json tree

标题听起来不太清楚,但如果JSON“有”孩子,我会在ID s的警报中显示ID树的|添加单词children,当“组”完成后,我将添加|以显示该组已结束,问题是我无法找到添加[ { "name": "node1", "id": 1, "is_open" :true, "children": [ { "name": "child2", "id": 3 }, { "name": "child2", "id": 7 }, { "name": "child1", "id": 2 } ] }, { "name": "node1", "id": 4, "is_open": true, "children": [ { "name": "child2", "id": 5 } ] } ] 时的方法小组结束了。

所以,这棵树:

ID:1

将显示为:

  

1,儿童,3,7,2 | 4,儿童,5 |

因此,我知道childrenID:3ID:7ID:2|,因为{{1}管道符号等等,但我不知道如何创建要检查的内容并添加|。你能救我吗?

提前致谢。

我的代码:

var data = '[{"name":"node1","id":1,"is_open":true,"children":[{"name":"child2","id":3},{"name":"child2","id":7},{"name":"child1","id":2}]},{"name":"node1","id":4,"is_open":true,"children":[{"name":"child2","id":5}]}]';
var arrays = [];
//convert you string to object
//or you can simply change your first row.
data = $.parseJSON(data);
//function to loop the array
function listNodes(inputVal) {
  if (jQuery.isArray(inputVal)) {
    $.each(inputVal, function(i, elem) {
      arrays.push(elem.id);
      console.log(elem);
      if (jQuery.isArray(elem.children)) {
        arrays.push('children');
        listNodes(elem.children);
      }
    });
  }
}
listNodes(data);
alert(arrays);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

更新

如果我有两个或更多级别的孩子怎么办?

var data = JSON.parse('[{"name":"node1","id":1,"is_open":true,"children":[{"name":"child2","id":7},{"name":"child1","id":2,"is_open":true,"children":[{"name":"child2","id":3}]}]},{"name":"node1","id":4,"is_open":true,"children":[{"name":"child2","id":5}]}]');

var result = data.map(function(item) {
    return [item.id].concat('children', item.children.map(function(subitem) {
        return subitem.id;
    }));
}).join('|');

alert(result);

3 个答案:

答案 0 :(得分:3)

你不需要jQuery。对于脚本的简化版本,您可以将原始Array.prototype.mapconcat一起使用:

var data = JSON.parse('[{"name":"node1","id":1,"is_open":true,"children":[{"name":"child2","id":3},{"name":"child2","id":7},{"name":"child1","id":2}]},{"name":"node1","id":4,"is_open":true,"children":[{"name":"child2","id":5}]}]');

var result = data.map(function(item) {
    return [item.id].concat('children', item.children.map(function(subitem) {
        return subitem.id;
    }));
}).join('|');

alert(result);

或者,如果您想了解自己的代码修复后的外观:

function listNodes(inputVal) {
    if (jQuery.isArray(inputVal)) {
        $.each(inputVal, function (i, elem) {
            arrays.push(elem.id, ',');
            if (jQuery.isArray(elem.children)) {
                arrays.push('children,', elem.children.map(function(el) { return el.id; }));
            }
            arrays.push('|');
        });
    }
    arrays = arrays.join('');
}

答案 1 :(得分:1)

试试这个:

var data = [{"name":"node1","id":1,"is_open":true,"children":[{"name":"child2","id":3},{"name":"child2","id":7},{"name":"child1","id":2}]},{"name":"node1","id":4,"is_open":true,"children":[{"name":"child2","id":5}]}];

var str = '';
//1,children,3,7,2|4,children,5|
$.each(data, function(i, item){
    if(item.id){
      str += item.id + ',children,'
       $.each(item.children, function(j, child){
          if(child.id){
             str += child.id;
             str += (j >= item.children.length-1) ? "|" : ",";
          }
         
      });
    }
});

alert(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 2 :(得分:0)

我已经为任何类型的json对象编写了一个递归函数来进行层次打印..它在java中...你可以调整它来使用它..

static void printRecursive(JSONObject obj) {   
for(Object key:obj.keySet()) {
       //System.out.println(obj.get(key.toString()).getClass().getSimpleName());
        if(obj.get(key.toString()) instanceof JSONArray) {
            JSONArray aobj = ((JSONArray)obj.get(key.toString())); 

            for(int i=0;i<aobj.length();i++) {
                System.out.println(key.toString());
                printRecursive(aobj.getJSONObject(i));
            }
        }
        else
        if(obj.get(key.toString()) instanceof JSONObject) {
            System.out.println(key.toString());
            printRecursive((JSONObject)obj.get(key.toString()));
        }
        else
            System.out.println(key.toString()+" -> "+obj.get(key.toString()));
    }
}