您好,我正在努力转换一个 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);
关于javascript - 我如何在 javascript 中编写以下 php 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52491571/