简体   繁体   中英

How to parse JSON having nested arrays in javascript or jquery

I want to parse JSON like below

{
   "nodeId":3892718504,
   "root":true,
   "subs":[
      {
         "nodeId":3892717286
      },
      {
         "nodeId":3892716092,
         "subs":[
            {
               "nodeId":3892715856,
               "subs":[
                  {
                     "nodeId":3892718592,
                     "subs":[
                        {
                           "nodeId":3892717580
                        }
                     ]
                  }
               ]
            }
         ]
      },
      {
         "nodeId":3892717497
      }
   ]
}

Each node can have subs and those subs can have nodes that can have their own subs. all I want is an array having all nodeId, how can I parse this JSON such that an array called nodes_list is populated with all nodeId. I can use javascript or jquery.

I'm trying the following approach to get an array of nodeId

jQuery.each(response.topology, function(i,obj) {
  if(i == "nodeId") {
    node_list.push(obj)
  }
  if(i == "subs"){
    jQuery.each(i, function(key,value) {
        if(i == "nodeId") {
            node_list.push(obj)
        }
    }
  }
});

I just need a little hint on how it can be in an iterative manner.

This can be done with function generators.

Perhaps not the most enjoyable approach, but I'm pretty sure the other solutions will already imply using other ways, so here is a solution using generators.

PS: Beware of browser support: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield

 const input = { "nodeId":3892718504, "root":true, "subs":[ { "nodeId":3892717286 }, { "nodeId":3892716092, "subs":[ { "nodeId":3892715856, "subs":[ { "nodeId":3892718592, "subs":[ { "nodeId":3892717580 } ] } ] } ] }, { "nodeId":3892717497 } ] }; function* nodeLookup(obj) { if (obj.nodeId) yield obj.nodeId; if (obj.subs) for (var i = 0; i < obj.subs.length; i++) yield *nodeLookup(obj.subs[i]); }; const node_ids = [...nodeLookup(input)]; console.log(node_ids); 

Just use recursion to iterate over subs

var nodeIds = [];
if (data.nodeId) nodeIds.push(data.nodeId);
function fetchNodeIds (subs) {
    if (!subs.length) return cb([]);
    var abc = [];
    subs.forEach(function (sub) {
        abc.push(sub.nodeId);
        if (sub.subs && sub.subs.length) abc = abc.concat(fetchNodeIds(sub.subs))
    });
    return abc;
}
nodeIds = nodeIds.concat(fetchNodeIds(data.subs));
console.log('--All nodeIds--', nodeIds)

It's straightforward to do recursively:

 const gatherIds = ({nodeId, subs}, results = []) => subs ? [...results, nodeId, ...(subs .flatMap (sub => gatherIds (sub, results) ))] : [...results, nodeId] const response = {"nodeId": 3892718504, "root": true, "subs": [{"nodeId": 3892717286}, {"nodeId": 3892716092, "subs": [{"nodeId": 3892715856, "subs": [{"nodeId": 3892718592, "subs": [{"nodeId": 3892717580}]}]}]}, {"nodeId": 3892717497}]} console .log ( gatherIds (response) ) 

If your target environments don't support flatmap , it's easy enough to shim.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM