javascript - 在 Firebase JavaScript 中计数

标签 javascript jquery firebase count firebase-realtime-database

下面有一个示例 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
  } ]
}

在 JavaScript 中查找产品数量(计数)的最短方法是什么? Firebase 是否在 JavaScript 中提供任何查询来查找对象中的计数?

最佳答案

这是一个简单的解决方案。只需从 JSON 对象中获取所需数组的长度即可。

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);

JSON字符串的情况:像这样获取长度

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);

关于javascript - 在 Firebase JavaScript 中计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38719146/

相关文章:

java - 如何将 FirebaseApp.initializeApp 用于 FirebaseRemoteConfig

python - Firebase 数据库数据到 R

javascript - 如何知道点击了什么?

javascript - 使我的网站菜单触摸友好(下拉)

javascript - 在 jQuery DataTables 1.9 中,如何按 colspanned header 排序?

javascript - Angular 2 页面大小

javascript - 在 Firestore 中将 forEach 与单个文档查询一起使用?

javascript - 使用指令附加具有 html 元素范围访问权限的功能

javascript - 从网络浏览器获取 GPS 位置

javascript - 如何将日期选择器插入 MS Excel 单元格