[英]Adding an property with percent value of another property in json object javascript underscore
My base data 我的基础数据
[{
month: 'Jan',
cat: 'A',
val: 20
},{
month: 'Jan',
cat: 'B','
val: 5
},{
month: 'Jan',
cat: 'C',
val: 10
},{
month: 'Feb',
cat: 'A',
val: 30
},{
month: 'Feb',
cat: 'B',
val: 10
},{
month: 'Feb',
cat: 'C',
val: 20
}];
I would like to add another property called 'percent' to above object and its value would be the percent of property 'val' 我想在上面的对象中添加另一个名为'percent'的属性,它的值将是属性'val'的百分比
Any help is sincerely appreciated.. 任何帮助都是真诚的感谢..
Calculate the total using Array#reduce
method and then add percentage field using Array#forEach
method. 使用
Array#reduce
方法计算总数,然后使用Array#forEach
方法添加百分比字段。
var data = [{ month: 'Jan', cat: 'A', val: 20 }, { month: 'Jan', cat: 'B', val: 5 }, { month: 'Jan', cat: 'C', val: 10 }, { month: 'Feb', cat: 'A', val: 30 }, { month: 'Feb', cat: 'B', val: 10 }, { month: 'Feb', cat: 'C', val: 20 }]; var total = data.reduce(function(a, b) { return a + b.val }, 0); data.forEach(function(v) { v.percentage = (v.val * 100 / total).toFixed(2) }); console.log(data);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.