Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

Get values from an object in JavaScript [duplicate]

Writer Emily Wong

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?

2

6 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; }
}
5

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 want to do this in a single line, try:

Object.keys(a).map(function(key){return a[key]})
1

If you $ is defined then You can iterate

var data={"id" : 1, "second" : "abcd"};
$.each(data, function() { var key = Object.keys(this)[0]; var value = this[key]; //do something with value;
}); 

You can access it by following way If you know the values of keys

data.id

or

data["id"]
0

I am sorry that your concluding question is not that clear but you are wrong from the very first line. The variable data is an Object not an Array

To access the attributes of an object is pretty easy:

alert(data.second);

But, if this does not completely answer your question, please clarify it and post back.

Thanks !

1

Using lodash _.values(object)

_.values({"id": 1, "second": "abcd"})
[ 1, 'abcd' ]

lodash includes a whole bunch of other functions to work with arrays, objects, collections, strings, and more that you wish were built into JavaScript (and actually seem to slowly be making their way into the language).

1