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?

0

3 Answers 3

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"; 
Sign up to request clarification or add additional context in comments.

3 Comments

@user1519703, have you tried this code?
:I did, it gives undefined!!
... How? Did you copy my exact code?
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.

4 Comments

I suggest you reserve i and j for arrays and some other letter (I use o) for objects
@micha:Yeah i did try that! it says undefined!
Can you add the code you have tried?
i tried printing the value like: for(var i in some_Object){ alert(some_Object[i]); console.log(some_Object[i]); }
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.

1 Comment

I actually tried a few things and found an answer: var no_of_variables = Object.keys(some_object); thank you everyone for helping!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.