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?
No, JavaScript objects cannot have duplicate keys. The keys must all be unique.
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; } }
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With