Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a javascript object value without knowing the key [duplicate]

Tags:

Possible Duplicate:
How do I enumerate the properties of a javascript object?

If I have a javascript object like this :

data = {
    a : 2,
    b : 3
}

but a and b are arbitrary and decided at runtime. Is there any way to go through the object and access all properties without knowing the key?

like image 344
eric Avatar asked Sep 10 '12 02:09

eric


People also ask

How do you find the value of an object without the key?

How to get all property values of a JavaScript Object (without knowing the keys) ? Method 1: Using Object. values() Method: The Object. values() method is used to return an array of the object's own enumerable property values.

Can JS object have duplicate key?

In JavaScript, an object consists of key-value pairs where keys are similar to indexes in an array and are unique. If one tries to add a duplicate key with a different value, then the previous value for that key is overwritten by the new value.

How can I access a JavaScript object which has spaces in the object's key?

Use bracket notation to access a key that contains a space in an object, e.g. obj['my key'] . The bracket [] notation syntax allows us to access an object's key, even if it contains spaces, hyphens or special characters.


1 Answers

data = {
    a : 2,
    b : 3
}

for(var propName in data) {
    if(data.hasOwnProperty(propName)) {
        var propValue = data[propName];
        // do something with each element here
    }
}
like image 87
Elliot Bonneville Avatar answered Oct 24 '22 23:10

Elliot Bonneville