我想使用jquery / javascript根据e值对json数据进行分类。例如。如果e:0,则将其存储在单独的array1中并获取计数,如果e:1将其存储在array2中并获取计数,依此类推。这是我的json文件item.json
{
"mydata":[
{
"xvalue": "4 Oct 2015",
"yvalue": 53,
"e": 3
}, {
"xvalue": "5 Oct 2015",
"yvalue": 67,
"e": 3
}, {
"xvalue": "6 Oct 2015",
"time":"1.00 PM",
"yvalue": 99,
"e": 2
}, {
"xvalue": "7 Oct 2015",
"yvalue": 80,
"e": 1
}, {
"xvalue": "8 Oct 2015",
"yvalue": 160,
"e": 0
}]
}
如何将json文件和推送对象从json调用到数组?我的目标是计算每个类别e的百分比。下面是我粗略的代码片段,我知道它缺少很多东西,比如loop。请帮助完成它。
//some code for calling json, how to call I don't understand
var a0=[], a1=[], a2=[], a3=[]; //empty array for each category
var e0=0, e1=0, e2=0, e3=0; //counter for each category
if(e==0){
e0++;
}
if(e==1){
e1++;
}
if(e==2){
e2++;
}
if(e==3){
e3++;
}
var n= mydata.length; // calculate total no. of e's
e0per= (e0/n) *100;
e1per= (e1/n) *100;
e2per= (e2/n) *100;
e3per= (e3/n) *100;
console.log(e0per);
答案 0 :(得分:1)
data = {
"mydata":[
{
"xvalue": "4 Oct 2015",
"yvalue": 53,
"e": 3
}, {
"xvalue": "5 Oct 2015",
"yvalue": 67,
"e": 3
}, {
"xvalue": "6 Oct 2015",
"time":"1.00 PM",
"yvalue": 99,
"e": 2
}, {
"xvalue": "7 Oct 2015",
"yvalue": 80,
"e": 1
}, {
"xvalue": "8 Oct 2015",
"yvalue": 160,
"e": 0
}]
};
// Here's the actual categorization part
categories = {};
for (var i = 0; i < data.mydata.length; i++) {
var item = data.mydata[i];
var e = item.e;
if (!(e in categories)) categories[e] = [];
categories[e].push(item);
}
console.log(categories)
这种方法的好处在于,您不必担心"e"
索引可能具有的不同值 - 第一次创建一个新的唯一值{{1被发现了。