这是我的JSON数据:
{
"EF": [
{
"OP": "op1",
"pound": 2000,
"Date": "2012-1-13T00:00:00.000Z"
},
{
"OP": "op1",
"pound": 1800,
"Date": "2014-12-6T00:00:00.000Z"
},
{
"OP": "op2",
"pound": 300,
"Date": "2013-6-1T00:00:00.000Z"
}
]
}
我希望计数每个参数值,排序它们从最大到最小,以得到这样的表:
OP:op1(2),OP2(1)磅:2000,1800,300日期: 2014-12-6T00:00:00.000Z,2013-6-1T00:00:00.000Z, 2012-1-13T00:00:00.000Z
我尝试使用d3.nest(),但我没有取得多大成功。有什么想法吗?
答案 0 :(得分:1)
//JSON from db?
var json = {
"EF": [{
"OP": "op1",
"pound": 2000,
"Date": "2012-1-13T00:00:00.000Z"
}, {
"OP": "op1",
"pound": 1800,
"Date": "2014-12-6T00:00:00.000Z"
}, {
"OP": "op2",
"pound": 300,
"Date": "2013-6-1T00:00:00.000Z"
}]
};
//Sort based on pound
json.EF.sort(function(a, b) {
if (a.pound < b.pound) return 1;
if (a.pound > b.pound) return -1;
return 0;
});
var hash = {}; //Keep track of counts
//Count the values
for (var i in json.EF) {
var obj = json.EF[i];
if (hash[obj.OP]) {
hash[obj.OP] += 1;
} else {
hash[obj.OP] = 1;
}
}
//Sorted
console.log("SORTED:", json);
console.log("COUNTS:", hash);
//Now, when you loop through the json to display the values, just check the counts and display them
&#13;