Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 700
Hari krishnan Avatar asked Jul 14 '13 01:07

Hari krishnan


People also ask

Does JavaScript object allow for duplicate keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.


2 Answers

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;     } } 
like image 114
cfs Avatar answered Oct 13 '22 06:10

cfs


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]) 
like image 36
trincot Avatar answered Oct 13 '22 05:10

trincot