我在該json文件中有一個json值三個電影的名字。 JSON數據是動態數據。我想計算在WinProbability
字段上的百分比。我想輸出如下如何獲取json的唯一值並在數組中求和另一個值?
movie_name = [ "12 Years a Slave", "American Hustle", "Captain"]
percentage = [ 3.47, 2.54, 4.22]
我的JSON文件中顯示
[
{
"ID":1,"Nominee":"12 Years a Slave","WinProbability":0.00,"WinType":"Win"
},
{
"ID":2,"Nominee":"12 Years a Slave","WinProbability":2.81,"WinType":"Win"
},
{
"ID":3,"Nominee":"12 Years a Slave","WinProbability":0.66,"WinType":"Nominated"
},
{
"ID":1,"Nominee":"American Hustle","WinProbability":1.62,"WinType":"Nominated"
},
{
"ID":2,"Nominee":"American Hustle","WinProbability":0.85,"WinType":"Win"
},
{
"ID":3,"Nominee":"American Hustle","WinProbability":0.07,"WinType":"Win"
},
{
"ID":1,"Nominee":"Captain Phillips","WinProbability":2.70,"WinType":"Nominated"
},
{
"ID":2,"Nominee":"Captain Phillips","WinProbability":0.00,"WinType":"Win"
},
{
"ID":3,"Nominee":"Captain Phillips","WinProbability":1.52,"WinType":"Win"
}
]
我的jQuery代碼
$(function() {
$.getJSON('movie.json', function(data) {
var movie_name = [],
percentage = [];
data.forEach(function(obj) {
if (movie_name.indexOf(obj.Nominee) == -1)
movie_name.push(obj.Nominee);
var lastIndex = movie_name.length - 1;
if (typeof percentage[lastIndex] == "undefined")
percentage.push(obj.WinProbability);
else
percentage[lastIndex] += obj.WinProbability;
});
console.log(movie_name);
console.log(percentage);
});
});
請幫助我如何做到這一點。我嘗試了提名的唯一名稱,但我不知道要添加WinProbability
並計算百分比。
可能改變數據到下面格式
{
"Win": [
{
"0": 3.47,
"name": "12 Years a Slave"
},{
"0": 2.54,
"name": "American Hustle"
},{
"0": 4.22,
"name": "Captain Phillips"
}
],
"Nominated":[
{
"0": 1.2,
"name": "12 Years a Slave"
},{
"0": 1,
"name": "American Hustle"
},{
"0": 1,
"name": "Captain Phillips"
}
]
}
我覺得你的計算是錯誤的。 '12年奴隸'的總和應該是'3.47' – Mohammad
@Mhamhammad是的,我真的把虛擬值 –
你有任何代碼? – Mohammad