I have a JSON array being returned, and I want to loop through it to display the data in a table:
{"confirmed":"362.53","not_confirmed":"9,403.87","payouts":{"confirmed":{"2023-04-05":36253},"submitted":{"2023-04-12":900,"2023-04-11":9600},"pending_submission":{"2023-04-13":897694,"2023-05-04":32193}}}
I tried using this for loop inside my ajax call, but what I see in the console is just Object object
$.ajax({
type: "GET",
url: ""
dataType: 'json',
success: function(data) {
for(var i in data.payouts) {
console.log(data.payouts[i]);
}
}
});
2
Answers
Inside the
$.each()
function, the code logs a message to the console for each of the nested properties of payouts. Specifically, it logs the value of the confirmed property of that nested object.Try below snippet
data.payouts
is not an array, it is an object that contains a set of keys and values. To iterate over objects, you can use a method from theObject
class (docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object).To iterate over keys and values, fetching both in each iteration, you can use
Object.entries()
like this:I used
for..of
to get the values instead of usingfor..in
and getting the index of each item in the array returned by theObject.entries()
method.Note that the value in every entry is also an object, so you need to use the same logic for each one of them if you want to process them.