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?
This question is related to
javascript
function
object
use
console.log(variable)
and if you using google chrome open Console by using Ctrl+Shift+j
Goto >> Console
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]})
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"]
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 !
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).
Source: Stackoverflow.com