Hari krishnan Hari krishnan - 1 month ago 7
Javascript Question

Get values from an object in JavaScript

I have this object:

var data = {"id": 1, "second": "abcd"};


These are values from a form. I am passing this to a function for verification.

If the above properties exist we can get their values with
data["id"]
and
data["second"]
, but sometimes, based on other values, the properties can be different.

How can I get values from
data
independent of property names?

cfs cfs
Answer

What you have is a javascript object, not an array, and you are addressing properties not indicies.

I think what you are trying to accomplish is to access the properties of an object without knowing the names of those properties. To do that you can use a for ... in loop:

for(key in data) {
    if(data.hasOwnProperty(key)) {
        var value = data[key];
        //do something with value;
    }
}
Comments