2

I have a simple JSON object, but the problem is that the key can change which means I can't call the data with its key name. My aim is to present the data in a table layout.

This is one example of how I get the data:

[{"domain":"animals","country":"Argentina"}]

But it can also be that I get this result

[{"fruits":"apple","country":"Argentina", "value": "1234"}]

Now I could find out how to get the keys:

var dataKeys = []
for( var key in data[ 0 ] ) {
  dataKeys.push( key );
  console.log(key);
}

Very well, now I have the names for the columns. But from here I have no clue how to get the values to each key.

var dataKeys = []
for( var key in data[ 0 ] ) {
  dataKeys.push( key );
  //console.log(key);
}
//console.log(result.join());
for( var x in data ) {
   for (var i in dataKeys) {
      console.log(data[dataKeys[i]]);
   };
}

But the console shows "undefined".

0

2 Answers 2

1

You have to consider the index variable x in the loop.

for( var x in data ) {
   for (var i in dataKeys) {
      console.log(data[x][dataKeys[i]]);
   };
}

on a related note, the keys can be achieved by

dataKeys = Object.keys(data[0])

also

hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this if i am not wrong-

var json = '[{"domain":"animals","country":"Argentina"},   {"fruits":"apple","country":"Argentina", "value": "1234"}]';
var data= JSON.parse(json);
$.each(data,function(key,val){
    alert("Main object at Index: "+ key);
    $.each(val,function(i,v){
        alert(i + ': ' + v);
    });
});

Live demo : click here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.