1

I have a javascript issue.
If I have an object array objAr, the object consists of id,name.

If I was to access objAr[0].id it returns the id value of the first object. What would happen if the object is dynamic and therefore I do not know what it consists of, is there a way to dynamically call the Object attribute?

Currently I am creating another array

var theArr = new Array("id", "name");

and call:

objAr[0].theArr[0] instead of objAr[0].id.

Is there a way to do this better using Javascript?

2 Answers2

0

With Javascript you can call all of the attributes in an object without knowing the keys.
See below:

for(key in objAr[0]) {
   console.log(objAr[0][key]);
}

If you just wanted the first attribute you could run:

for(key in objAr[0]) {
   var attFirst = objAr[0][key];
   break;
}

Additionally for the JS array you could have used square brackets.

var theArr = ["id", "name"];

hope that helps

Craig Taub
  • 4,169
  • 1
  • 19
  • 25
  • 1
    Remember the `if (objAr[0].hasOwnProperty(key))` check to avoid iterating over the...'inherited'/'native' properties of the object (unless you really want to). – David Thomas Feb 11 '13 at 12:10
  • The _"first attribute"_ sample can do without the `for` loop, I'd suggest using a `if`, instead. – Cerbrus Feb 11 '13 at 12:11
  • this worked, useful to know additional stuff thanks –  Feb 11 '13 at 12:13
0

In javascript you can always use the "array notation" in place of the "dot notation"

So these 2 lines are the same

objAr[0].id
objAr[0]["id"]
Jamiec
  • 133,658
  • 13
  • 134
  • 193