简体   繁体   中英

How to return a value from an Object Literal based on a key?

I have an array as follows. How would I retrieve the value of a specific key and put that value in a variable?

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

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

You can do this via dot or bracket notation, like this:

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're after. Also, for clarity what you have is just an object, not an array :)

Here is a 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 Underscore JS library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM