0

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.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Ante
  • 85
  • 2
  • 8

3 Answers3

1

try this,

let a = [];
let b = [];
let c = [];

const data = [{"a":1, "b":2, "c":3}];

data.forEach( function(item, index) {
  Object.keys(item).forEach(function(i, ind) {
     eval(i+'.push('+item[i]+')');
  })
});
  
console.log('a is=', a, 'b is =', b, 'c is =', c);
Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118
0

You were on the right track but syntax was incorrect. You will have to use data[i][x[1]] instead. In your example "data" has no "x" attribute so it was causing error.

Shirish Goyal
  • 510
  • 2
  • 9
0

Encase the entire x[1] in square brackets to use it as the key - otherwise, you're trying to access the first item in data[i].x which doesn't exist:

one.push(data[i][x[1]]);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79