get variables of an object in javascript

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?


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";

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.


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.

链接地址: http://www.djcxy.com/p/27358.html

上一篇: 你如何使用JSON与唯一密钥一起工作?

下一篇: 在javascript中获取对象的变量