Skip to content Skip to sidebar Skip to footer

How To Get The Number Of Element In A Root Json Elment

I'm trying to get the number of elements in each node of a Json. For example in this case: { 'tickets': { 'use': 'Valida', 'useagain': 'Valida di nuovo', 'usetitle':

Solution 1:

try this way

Object.keys( obj ).forEach( function(key){
  console.log( "It has " + Object.keys(obj[key]).length + " " + key );
});

where obj is the object variable name.

Solution 2:

You can use Object.keys() on an object to get an array of its keys; then, use the array's length property to find the number of keys in the array.

So, if your JSON structure is yourJSON, you can do:

var ticketsNum  = Object.keys(yourJSON.tickets).length; // 4var faresNum    = Object.keys(yourJSON.fares).length; // 4var quantityNum = Object.keys(yourJSON.quantity).length; // 1

For nested data, like you have here, you could easily write a function that will count the key/value pairs of each of the "top-level" keys:

functioncountKeys (obj) {
    var count = {};
    Object.keys(obj).forEach(function (key) {
        count[key] = Object.keys(obj[key]).length;
    });
    return count;
}

var nums = countKeys(yourJSON);
// nums = { tickets: 4, fares: 4, quantity: 1 }

Solution 3:

Modern Browsers have an Objects.keys that can help you, generraly it used like this:

Object.keys(jsonArray).length;

Solution 4:

Maybe something like this:

var ticket =  {
     "tickets": 
     {
        "use": "Valida",
        "useagain": "Valida di nuovo",
        "usetitle": "Convalida biglietto",
        "price": "Prezzo"
     },
     "fares": 
     {
        "nofarestopurchase": "Non è possibile acquistare biglietti per la tratta indicata",
        "purchasedcongratulations": "Congratulazioni",
        "farepurchased": "Hai acquistato il tuo biglietto. Lo puoi trovare nella sezione",
        "mytickets": "I miei biglietti",
        "fareguestcard": "Hai ottenuto il tuo biglietto. Lo puoi trovare nella sezione"
     },
     "quantity": 
     {
        "title": "Seleziona il numero di persone:"
     }
}

var result = {};

for(prop in ticket) { 
   if(ticket.hasOwnProperty(prop)) {
      result[prop] = { length: Object.keys(ticket[prop]).length };
   }
}

console.log(JSON.stringify(result)); // {"tickets":{"length":4},"fares":{"length":5},"quantity":{"length":1}}

Solution 5:

Well you can try recursion. Yes this is little slow, but will be scalable.

For demonstration purpose, I have updated json to show nested objects.

JSFiddle.

var data = {
  "tickets": {
    "use": "Valida",
    "useagain": "Valida di nuovo",
    "usetitle": "Convalida biglietto",
    "price": "Prezzo"
  },
  "fares": {
    "nofarestopurchase": "Non è possibile acquistare biglietti per la tratta indicata",
    "purchasedcongratulations": "Congratulazioni",
    "farepurchased": "Hai acquistato il tuo biglietto. Lo puoi trovare nella sezione",
    "mytickets": "I miei biglietti",
    "fareguestcard": "Hai ottenuto il tuo biglietto. Lo puoi trovare nella sezione"
  },
  "quantity": {
    "title": "Seleziona il numero di persone:"
  },
  "test": [1, 2, 3, 4, 5],
  "test2": {
    "foo": {
      "a": 1,
      "b": 2
    }
  }
}

functiongetCount(obj, result) {
  if (typeof(obj) === "object" || Array.isArray(obj)) {
    Object.keys(obj).forEach(function(_key) {
      return (function(key) {
        if (typeof(obj[key]) === "object" || Array.isArray(obj[key])) {
          result = result || {};
          result[key] = {};
          result[key].count = Object.keys(obj[key]).length;
          Object.keys(obj[key]).forEach(function(k) {
            getCount(obj[key], result[key]);
          });
        }
      })(_key)
    });
  }
}

var r = {};
getCount(data, r);
console.log(r);

Post a Comment for "How To Get The Number Of Element In A Root Json Elment"