1

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",
5
  • 3
    Put what you want into an array and use array.join(', ') Commented Jun 23, 2022 at 2:41
  • your answer solved my issue for joining with comma, but how can i remove " ' " sign on my array? Commented Jun 23, 2022 at 2:56
  • I don't see any ' sign. Commented Jun 23, 2022 at 2:57
  • the result is ['12', '5', '1',] but i want to modify into [12, 5, 1] Commented Jun 23, 2022 at 3:09
  • You'll get that if you log the array, not if you use array.join(', '). Commented Jun 23, 2022 at 3:11

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.