Pranesh U H Pranesh U H - 3 months ago 14
Javascript Question

Count in Firebase JavaScript

I have a sample JSON object below:

{
"product" : [ {
"description" : "This ball has air it.",
"id" : "product0",
"name" : "football",
"price" : 10
}, {
"description" : "Can kick upto long distance.",
"id" : "product1",
"name" : "soccer boots",
"price" : 5
}, {
"description" : "Long socks",
"id" : "product2",
"name" : "stockings",
"price" : 2
}, {
"description" : "This ball has air it.",
"id" : "product3",
"name" : "gloves",
"price" : 3
}, {
"description" : "Wear it pls.",
"id" : "product4",
"name" : "jersey",
"price" : 12
} ]
}


What can be the shortest way to find the number (count) of products in JavaScript? Does Firebase provide any query in JavaScript to find the count in an object?

Answer

Here is a simple solution. Just get the length of required array from the JSON Object.

var json = {
  "product": [{
    "description": "This ball has air it.",
    "id": "product0",
    "name": "football",
    "price": 10
  }, {
    "description": "Can kick upto long distance.",
    "id": "product1",
    "name": "soccer boots",
    "price": 5
  }, {
    "description": "Long socks",
    "id": "product2",
    "name": "stockings",
    "price": 2
  }, {
    "description": "This ball has air it.",
    "id": "product3",
    "name": "gloves",
    "price": 3
  }, {
    "description": "Wear it pls.",
    "id": "product4",
    "name": "jersey",
    "price": 12
  }]
};

console.log(json.product.length);

Incase of JSON string: Get the length like this

var json = '{  "product" : [ {"description" : "This ball has air it.","id" : "product0","name" : "football","price" : 10  }, {"description" : "Can kick upto long distance.","id" : "product1","name" : "soccer boots","price" : 5  }, {"description" : "Long socks","id" : "product2","name" : "stockings","price" : 2  }, {"description" : "This ball has air it.","id" : "product3","name" : "gloves","price" : 3  }, {"description" : "Wear it pls.","id" : "product4","name" : "jersey","price" : 12  } ]}';

var t = JSON.parse(json);

console.log(t.product.length);