[
{
color: "red",
value: "#f00"
},
{
color: "green",
value: "#0f0"
},
{
color: "blue",
value: "#00f"
},
{
color: "cyan",
value: "#0ff"
},
{
color: "magenta",
value: "#f0f"
},
{
color: "yellow",
value: "#ff0"
},
{
color: "black",
value: "#000"
}
]
计算json密钥与
不同function count(obj) {
var count=0;
for(var prop in obj) {
if (obj.hasOwnProperty(prop)) {
++count;
}
}
return count;
}
到
var keys = [];
$.each(data, function(key, value) {
keys.push(key)
});
// numberOfKeys should equal to 2
var numberOfKeys = keys.length;var keys = [];
$.each(data, function(key, value) {
keys.push(key)
});
// numberOfKeys should equal to 2
var numberOfKeys = keys.length;
但是,如果我有一个特定的密钥,我只需像我的样本一样计算color
的数量或计算'红色'的数量。
计算现有(特定)密钥Example count color
计算现有(特定)值Example count red
答案 0 :(得分:0)
请参阅以下代码:
var json = [
{
color: "red",
value: "#f00"
},
{
color: "green",
value: "#0f0"
},
{
color: "blue",
value: "#00f"
},
{
color: "cyan",
value: "#0ff"
},
{
color: "magenta",
value: "#f0f"
},
{
color: "yellow",
value: "#ff0"
},
{
color: "black",
value: "#000"
}
]
转换为字符串:
var str = JSON.stringify(json)
使用正则表达式计算字符串如下(这不是一个完美的正则表达式,你可以更多地增强它,但这会起作用):
var colorCount = (str.match(/\"color\"/g) || []).length;//7
var redCount = (str.match(/\"red\"/g) || []).length;//1
可替换地:
var countColor = 0;
var countRed = 0;
for (var obj in json) {
console.log(json[obj])
var object = json[obj];
if (object.hasOwnProperty('color')) {
countColor++;
if(object.color == "red") {
countRed++;
}
}
}
console.log(countColor);
console.log(countRed);
编辑:
如果您担心json的级别(嵌套)可能比您想象的要大,那么您可以对json对象使用递归。