Get values from an object in JavaScript [duplicate]
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?
Solution 1:
To access the properties of an object without knowing the names of those properties you can use a for ... in
loop:
for(key in data) {
if(data.hasOwnProperty(key)) {
var value = data[key];
//do something with value;
}
}
Solution 2:
In ES2017 you can use Object.values()
:
Object.values(data)
At the time of writing support is limited (FireFox and Chrome).All major browsers except IE support this now.
In ES2015 you can use this:
Object.keys(data).map(k => data[k])