Habibi
Habibi

Reputation: 53

JSON Object into Comma Separated String

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",

Upvotes: 1

Views: 1994

Answers (1)

Barmar
Barmar

Reputation: 782130

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>

Upvotes: 1

Related Questions