1

I have this json:

var myjson = [
    {"ID":1, "FullName":"Breese Dantour"},
    {"ID":2, "FullName":"Danny Xirjav"},
    {"ID":3, "FullName":"Ben Falco"}
]

And I tried to catch it by it's key using an array:

var mykey = new array();
mykey.push("ID");
mykey.push("FullName");

var res = "";
for (var i = 0; i < myjson.length; i++) {
   var inner;
   for (var c=0; c < mykey.length; c++){
      inner = inner + "<td>" + myjson[i].mykey[c] + "</td>";
   }
   res = res + "<tr>" + inner + "</tr>\n";
}
alert(res);

And i got this error :

Error: TypeError: myjson[i].mykey is undefined

I know this happen because mykey is not the key of myjson. But I want that mykey returning it's value so it read as myjson key.
Any other ways?

3
  • 3
    Use myjson[i][mykey[c]] Commented May 7, 2014 at 8:39
  • Also var mykey = new array(); should be var mykey = new Array(); Commented May 7, 2014 at 8:46
  • @OkiErieRinaldi I've updated my answer with explanation ;) Commented May 7, 2014 at 8:47

3 Answers 3

2

Try this :

var mykey = new array();
mykey.push("ID");
mykey.push("FullName");

var res = "";
for(var i = 0; i < myjson.length; i++){
   var inner = "";
   for (var c=0; c < mykey.length; c++){
      inner = inner+"<td>"+myjson[i][mykey[c]]+"</td>";
   }
   res = res+"<tr>"+inner+"</tr>\n";
}
alert(res);
Sign up to request clarification or add additional context in comments.

Comments

1

Replace myjson[i].mykey[c] by myjson[i][mykey[c]]

The reason this works is that the dot operator(.) has higher precedence than [] so the former expression is evaluated as (myjson[i].mykey)[c] which gives you undefined because myjson[i] doesn't have the property mykey.

Comments

1

You can get array elements by key like this:

myjson[i][ mykey[c] ];

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.