How to return a value from a Literal object based on a key?

I have an array as follows. How can I get the value of a particular key and put that value in a variable?

var obj = {"one":"1","two":"3","three":"5","four":"1","five":"6"}; 

So, for example, if I want to get the value "three", how would I do it in javascript or jQuery?

+6
javascript jquery
source share
2 answers

You can do this via dot or bracket , for example:

 var myVariable = obj.three; //or: var myVariable = obj["three"]; 

In the second example, "three" could be a string in another variable, which is probably what you need. Also, for clarity, you only have an object, not an array :)

+11
source share

Here is the solution (by the way, this is an object, not an array):

 var obj = {"one":"1","two":"3","three":"5","four":"1","five":"6"}; var myFunc = function(thisObj, property) {console.log(obj[property])}; myFunc(obj, "two"); //Output will be 3 

You can also do this more easily using the _.pluck function from the JS Underscore library.

+2
source share

All Articles