0

Possible Duplicate:
How to list the properties of a javascript object

I am making an application that receives a JSON object from some services. This object is parsed using JSON.parse() and a JavaScript Object is returned.

Is there any way possible that I can find out the different variables present inside the object?

Example:

var some_object
{
    var a: "first"
    var b: "second"
}

I need to figure out a way to get names of a and b from this object some_object

Are there any predefined methods in JavaScript that do this?

Community
  • 1
  • 1

3 Answers3

2

This'll do the trick:

for (var key in some_object) { 
    console.log(key, some_object[key]);
}

However, you need to initialise your object differently:

var some_object = {
    a: "first",  // Note: Comma here,
    b: "second", // And here,
    c: "third"   // But not here, on the last element.
}

Result:

a first
b second

So, in my for loop, key is the name of the value, and some_object[key] is the value itself.

If you already know the variables(' names) in a object, you can access them like this:

console.log(some_object.a) // "first";
//or:
console.log(some_object["b"]) // "second";
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
0

You can do something like this:

var myObject = {
  abc: 14, 
  def: "hello"
}

for (var i in myObject ) { 
  alert("key: " + i + ", value: " + myObject[i]) 
}

In this case i will iterate over the keys of myObject (abc and def). With myObject[i] you can get the value of the current key in i.

Please note thate your object definition is wrong. Instead of

var a: "first"

you only have to use

a: "first"

inside objects.

micha
  • 47,774
  • 16
  • 73
  • 80
0

You should just be able to call some_object.a to get a, some_object.b to get b, etc.

You shouldn't be seeing var inside an object like that though. Object notation tends to look like this:

var some_object = {
    a: "first",
    b: "second"
}

Note, no var declarations, and a comma is used after every property of the object except the last.

guypursey
  • 3,114
  • 3
  • 24
  • 42
  • I actually tried a few things and found an answer: var no_of_variables = Object.keys(some_object); thank you everyone for helping! – user1519703 Jan 09 '13 at 16:50