javascript - 我如何在 javascript 中编写以下 php 代码?
问题描述
您好我正在转换一个 php 应用程序以继续计费,即使互联网无法正常工作。所以我将php代码转换为javascript。在这两者之间,我被困在了我的计费结束的地方。在这里,我需要将类似的税收百分比归为一个。有人可以让我知道怎么做吗?
$new_result = Array
(
[0] => Array
(
[tax] => SGST@2.5%
[percent] => 2.38
)
[1] => Array
(
[tax] => CGST@2.5%
[percent] => 2.38
)
[2] => Array
(
[tax] => CGST@9%
[percent] => 15.25
)
[3] => Array
(
[tax] => SGST@9%
[percent] => 15.25
)
[4] => Array
(
[tax] => SGST@2.5%
[percent] => 3.57
)
[5] => Array
(
[tax] => CGST@2.5%
[percent] => 3.57
)
)
$out = array();
foreach ($new_result as $key => $value){
if (array_key_exists($value['tax'], $out)){
$out[$value['tax']]['percent'] += ', '+$value['percent'];
} else {
$out[$value['tax']] = array('tax' => $value['tax'], 'percent' => $value['percent']);
}
}
输出 :
Array
(
[0] => Array
(
[tax] => SGST@2.5%
[percent] => 5.95
)
[1] => Array
(
[tax] => CGST@2.5%
[percent] => 5.95
)
[2] => Array
(
[tax] => CGST@9%
[percent] => 15.25
)
[3] => Array
(
[tax] => SGST@9%
[percent] => 15.25
)
)
我的尝试:
var out = [];
$.each(new_result, function(key,value5) {
if(value5.tax in out){
//
}else{
out[value5.tax] = [{tax:value5.tax, percent:value5.percent}];
}
});
输入数组
var newresult = [{"tax":"CGST@9%","percent":"76.27"},{"tax":"SGST@9%","percent":"76.27"},{"tax":"CGST@9%","percent":"15.25"},{"tax":"SGST@9%","percent":"15.25"},{"tax":"SGST@2.5%","percent":"3.57"},{"tax":"CGST@2.5%","percent":"3.57"}];
解决方案
在 javascript 中,您可以使用reduce
如下函数进行分组
var gst = [
{tax: 'SGST@2.5%', percent: 2.38},
{tax: 'CGST@2.5%', percent: 2.38},
{tax: 'CGST@9%', percent: 15.25},
{tax: 'SGST@9%', percent: 15.25},
{tax: 'SGST@2.5%', percent: 3.57},
{tax: 'CGST@2.5%', percent: 3.57}
];
var result = gst.reduce(function (acc, ele) {
var index = acc.findIndex(e => e.tax == ele.tax);
if (index == -1) {
acc.push({
tax: ele.tax,
percent: ele.percent
})
} else {
acc[index].percent += parseFloat(ele.percent);
acc[index].percent = acc[index].percent;
}
return acc;
}, []);
console.log(result);
推荐阅读
- angular - 角度弹性布局动态行高
- android - FloatingActionButton 放错地方了
- .net - windows 身份验证未显示在 iis windows 10 中
- batch-file - Pentaho Windows 任务计划程序
- python - 从类方法中提取重复代码
- angularjs - 为什么嵌套的 ng-repeat 不适用于 h1 标签?
- jquery - 如何禁用日期选择器的结束日期小于或等于动态字段的开始日期
- python - 检测是否在 TCP 套接字上调用了 `connect()`
- .htaccess - 为 facebook 爬虫重定向 htaccess
- java - KeyListener/KeyBindings 和添加组件的顺序