简体   繁体   中英

Count JSON objects Javascript

Ok so theres this JSON object:

    jsontext = {"switches":[{"dpid":"00-00-00-00-00-01"},{"dpid":"00-00-00-00-00-02"},{"dpid":"00-00-00-00-00-03"},{"dpid":"00-00-00-00-00-04"},{"dpid":"00-00-00-00-00-05"},{"dpid":"00-00-00-00-00-06"},{"dpid":"00-00-00-00-00-07"}],
"links":[["00-00-00-00-00-01","00-00-00-00-00-05"],["00-00-00-00-00-02","00-00-00-00-00-03"],["00-00-00-00-00-05","00-00-00-00-00-06"],["00-00-00-00-00-05","00-00-00-00-00-07"],["00-00-00-00-00-02","00-00-00-00-00-04"],["00-00-00-00-00-01","00-00-00-00-00-02"]]}

The goal is to count all the dpid objects that exist in it... so I do the following so far:

function objectLength(obj) {
  var result = 0;
  for(var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
    // or Object.prototype.hasOwnProperty.call(obj, prop)
      result++;
    }
  }
  return result;
}

The function that I call to get the amount of dpid's in switches

objectLength(jsontext.switches);

The issue is, when there is only one dpid for switches like this:

jsontext = {"switches":[{"dpid":"00-00-00-00-00-01"}],"links":[]}

it counts 0... it doesn't do anything in the for section... for some reason it assume its empty I guess..?

TL;DR why when only 1 dpid of switches exists is the json object it returns 0..

Cheers!

Since the switches property only seems to contain objects with dpid properties, you don't really have to do anything special to count them. Just do this:

var count = jsontext.switches.length;

You can just do by filtering and using the length property.

var arr = jsontext.switches.filter(function(x){return x.hasOwnProperty('dpid'); });
console.log(arr.length); // number of objects

DEMO

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