I have a JSON string in format
[{"DATE":"2019-01-01","A":0,"B":0}]
generated by a php script where there can be any number of keys with different key names and values.
What I am trying to do is access these key names when creating a js array.
This is easy when I know what the key names are:
$.ajax({
url: "data.php",
method: "GET",
success: function(data) {
let date = [];
let one = [];
let two = [];
for(let i in data) {
date.push(data[i].DATE);
one.push(data[i].A);
two.push(data[i].B);
}
...
I just push them into array by key name. But what if I don't know the key names beforehand (DATE, A and B in this example)?
I tried getting the key names and using them instead of static 'DATE', 'A' and 'B', which doesn't work. Example:
const x = Object.keys(data[0]);
console.log(x[1]);
This results in 'A', but I can't use it as one.push(data[i].x[1]);
to populate an array. The error in console is
"Uncaught TypeError: Cannot read property '1' of undefined".
I am searching for a solution and would appreciate your help understanding this problem.