首页 > 解决方案 > 我如何在 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"}];

标签: javascriptphpjqueryjson

解决方案


在 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);


推荐阅读