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