0

I'm trying to access the data from an array object:

{
    "results": [{
        "ID": "aaa",
        "12/06/2017": "1",
        "13/06/2017": "0",
        "14/06/2017": "1",
        "15/06/2017": "1",
        "16/06/2017": "0",
        "17/06/2017": "1",
        "18/06/2017": "0"
    }
    ]
}

I usually do this by:

    $.each(data.results, function (index, item) {
                    var eachrow = "<tr>"
                    + "<td>" + item.ID + "</td>"
                    ect...
    $('#tbody').append(eachrow);
                      }

but in this case the property names will change with each search so I can't just write them in. I do know what the values will be before searching so I can assign them to variables but item.variable doesn't work. I've tried: item.[variable] and item.arr[1] but i can't get anything to work.

Thanks for the help

james
  • 9
  • 1

1 Answers1

0

Assuming this is your result

const result = {
  "results":[
    {
      "ID":"aaa",
      "12/06/2017":"1",
      "13/06/2017":"0",
      "14/06/2017":"1",
      "15/06/2017":"1",
      "16/06/2017":"0",
      "17/06/2017":"1",
      "18/06/2017":"0"
    }
  ]
};

then what you can do to get all the key-value pair is

const firstResult = result.results[0];
Object.keys(firstResult)
  .map(key => {
    const value = firstResult[key];
    return { key, value };
  })
  .forEach(process);

And the process function is something like this:

const process = ({ key, value }) => {
  console.log(`The value of ${key} is ${value}`);
};
Egidio Caprino
  • 553
  • 10
  • 18