skip to Main Content

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


  1. 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

    let data = { "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 } } };
    $.each(data, function (index, element) {
        if (index == 'payouts') {
            console.log(element);
        }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    Login or Signup to reply.
  2. 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 the Object 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:

    const data = {"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}}};
    
    for (const [key, value] of Object.entries(data.payouts)) {
      console.log(key, "=>", value);
    }

    I used for..of to get the values instead of using for..in and getting the index of each item in the array returned by the Object.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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search