Traverse all the Nodes of a JSON Object Tree with JavaScript

前端 未结 16 1741
猫巷女王i
猫巷女王i 2020-11-22 06:26

I\'d like to traverse a JSON object tree, but cannot find any library for that. It doesn\'t seem difficult but it feels like reinventing the wheel.

In XML there are

16条回答
  •  感动是毒
    2020-11-22 07:18

    My Script:

    op_needed = [];
    callback_func = function(val) {
      var i, j, len;
      results = [];
      for (j = 0, len = val.length; j < len; j++) {
        i = val[j];
        if (i['children'].length !== 0) {
          call_func(i['children']);
        } else {
          op_needed.push(i['rel_path']);
        }
      }
      return op_needed;
    };
    

    Input JSON:

    [
        {
            "id": null, 
            "name": "output",   
            "asset_type_assoc": [], 
            "rel_path": "output",
            "children": [
                {
                    "id": null, 
                    "name": "output",   
                    "asset_type_assoc": [], 
                    "rel_path": "output/f1",
                    "children": [
                        {
                            "id": null, 
                            "name": "v#",
                            "asset_type_assoc": [], 
                            "rel_path": "output/f1/ver",
                            "children": []
                        }
                    ]
                }
           ]
       }
    ]
    

    Function Call:

    callback_func(inp_json);
    

    Output as per my Need:

    ["output/f1/ver"]
    

提交回复
热议问题