Get values from an object in JavaScript

JavascriptFunctionObject

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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])

Solution 3 - Javascript

If you want to do this in a single line, try:

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

Solution 4 - Javascript

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"]

Solution 5 - Javascript

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 !

Solution 6 - Javascript

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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHari krishnanView Question on Stackoverflow
Solution 1 - JavascriptcfsView Answer on Stackoverflow
Solution 2 - JavascripttrincotView Answer on Stackoverflow
Solution 3 - JavascriptErel Segal-HaleviView Answer on Stackoverflow
Solution 4 - Javascriptuser3118220View Answer on Stackoverflow
Solution 5 - JavascriptcooshalView Answer on Stackoverflow
Solution 6 - Javascriptcs01View Answer on Stackoverflow