Liz Banach Liz Banach - 2 months ago 13
Javascript Question

How to separate JSON array into 2 separate arrays of values with jQuery?

I have the following AJAX script pulling in a JSON array from a PHP file:

// get jsonData from inc/wip-data.php
var jsonData = $.ajax({
url: 'inc/wip-data.php',
dataType: 'json',
});


The JSON array is as follows:

[
{
"date": "2015-10",
"clientCostsTotal": "0.00"
},
{
"date": "2015-11",
"clientCostsTotal": "0.00"
},
{
"date": "2016-01",
"clientCostsTotal": "0.00"
},
{
"date": "2016-02",
"clientCostsTotal": "0.00"
},
{
"date": "2016-03",
"clientCostsTotal": "0.00"
},
{
"date": "2016-04",
"clientCostsTotal": "27962.50"
},
{
"date": "2016-05",
"clientCostsTotal": "174060.00"
},
{
"date": "2016-06",
"clientCostsTotal": "309000.00"
},
{
"date": "2016-07",
"clientCostsTotal": "502261.50"
},
{
"date": "2016-08",
"clientCostsTotal": "7598.00"
},
{
"date": "2016-12",
"clientCostsTotal": "0.00"
}
]


I need to grab all of the
date
values and store them in one array. Also, I need to grab all of the
clientCostsTotal
values and store them in a separate array. How do I do this?

Thank you for your help.

Answer

No need for jQuery, use a Array.forEach() like this:

var dates = [];
var clientCosts = [];

$.ajax({
  url: 'inc/wip-data.php',
  dataType: 'json'
}).done(function(data) {
  data.forEach(function(item) {
    dates.push(item.date);
    clientCosts.push(item.clientCostsTotal);
  });
});

There's an snippet below that demonstrates how this works (without the AJAX call).

var dates = [];
var clientCosts = [];
var data = [{
  "date": "2015-10",
  "clientCostsTotal": "0.00"
}, {
  "date": "2015-11",
  "clientCostsTotal": "0.00"
}, {
  "date": "2016-01",
  "clientCostsTotal": "0.00"
}, {
  "date": "2016-02",
  "clientCostsTotal": "0.00"
}, {
  "date": "2016-03",
  "clientCostsTotal": "0.00"
}, {
  "date": "2016-04",
  "clientCostsTotal": "27962.50"
}, {
  "date": "2016-05",
  "clientCostsTotal": "174060.00"
}, {
  "date": "2016-06",
  "clientCostsTotal": "309000.00"
}, {
  "date": "2016-07",
  "clientCostsTotal": "502261.50"
}, {
  "date": "2016-08",
  "clientCostsTotal": "7598.00"
}, {
  "date": "2016-12",
  "clientCostsTotal": "0.00"
}];

data.forEach(function(item) {
  dates.push(item.date);
  clientCosts.push(item.clientCostsTotal);
});

console.log(dates, clientCosts);

Comments