I have data sent from a php page and I want to save the 'date' and 'count' values into two different arrays in javascript. But I don't know how to access the data below. Any help?
{
"0": {
"date": "12/24/21",
"count": 1
},
"1": {
"date": "01/01/22",
"count": 1
},
"3": {
"date": "01/02/22",
"count": 2
},
"6": {
"date": "01/04/22",
"count": 3
},
"7": {
"date": "01/05/22",
"count": 1
},
"9": {
"date": "01/06/22",
"count": 2
}
}
javascript code:
$(document).ready(function(){
$.ajax({
url: "/ajax/page",
method: "GET",
success: function(data) {
let date = [];
let count = [];
// code to save the values from php page
},
error: function(data) {
console.log('error');
}
});
});
I think you may be missing some parenthesis and curly brackets in there after the success field. You might wanna fix it up a lil like:
$(document).ready(function () {
$.ajax({
url: "/ajax/page",
method: "GET",
success: function (data) {
let date = [];
let count = [];
// code to save the values from php page
for (keys in data) {
//do ya thang
}
},
error: function (data) {
console.log("error");
}
});
});
With it all nice and spruced up, you could utilize a few methods for iterating through that JSON object that's returned. You could either get the objects keys and use them to iterate through the object with Object.keys(yourObject), or you could use a for-in loop like above to iterate through the object.
Either way, you can iterate through the object and push the date and count vals for each field in the object onto your date and count arrays.
const data =
'{ "0": { "date": "12/24/21", "count": 1 }, "1": { "date": "01/01/22", "count": 1 }, "3": { "date": "01/02/22", "count": 2 }, "6": { "date": "01/04/22", "count": 3 }, "7": { "date": "01/05/22", "count": 1 }, "9": { "date": "01/06/22", "count": 2 } }';
const obj = JSON.parse(data);
const dateArr = [];
const countArr = [];
for (const value of Object.values(obj)) {
const { date, count } = value;
dateArr.push(date);
countArr.push(count);
}
console.log("dateArr", dateArr);
console.log("countArr", countArr);
this is quite straightforward, if your data is json, you need to parse it to Javascript first using JSON.parse, and then use Object.values and a loop to push your data to your variables.
Here I'm using for...of loop