Home > Enterprise >  JSON Object into Comma Separated String
JSON Object into Comma Separated String

Time:06-23

I have problem with converting JSON Object into string with comma separated,

Here's my code:

    $.ajax({
        url:'<?= site_url('chartstatus') ?>',
        method:'get',
        success:function(response){
            var nama_status = [];
            let jumlah=null;
            $.each(response.chartstatus,function(key, value){
              status = value['abs_status'].toString();
              nama_status = '"' status '"' ", ";
              jum = value['total'];
              jumlah = jum ", ";
              
            });
            console.log(nama_status);
            console.log(jumlah);
        } 
        });
    }

But the result is always only put first value into variable,

Here's my ajax response:

{
 chartstatus: [
 {
  abs_status: "Bekerja",
  total: "12"
  },
  {
  abs_status: "Tanpa Keterangan",
  total: "5"
  },
  {
  abs_status: "Hari Libur",
  total: "1"
 }
 ]
}

I want result like this :

12, 5, 1,

and

"Bekerja", "Tanpa Keterangan", "Hari Libur",

CodePudding user response:

Push each value into an array and then use .join() to make a comma-delimited string.

const response = {
  chartstatus: [{
      abs_status: "Bekerja",
      total: "12"
    },
    {
      abs_status: "Tanpa Keterangan",
      total: "5"
    },
    {
      abs_status: "Hari Libur",
      total: "1"
    }
  ]
}

let nama_status = [];
let jumlah = [];

$.each(response.chartstatus, function(key, value) {
  status = value.abs_status.toString();
  nama_status.push('"'   status   '"');
  jumlah.push(value.total)

});
console.log(nama_status.join(', ')); 
console.log(jumlah.join(', '));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  • Related