Find item by key in Javascript

A quick beginner asks.

Suppose I have a javsacript object:

var meh=[["cars",27], ["bikes",85], ["skates",4]];

To go through each data object here, I can do this:

$.each(meh, function(index,value){        
    console.log(value) //returns ["cars",27] etc..
 });

And given that I know the place of, say, cars, I can do this to get access to it:

console.log(meh[0][0]) //shows "Cars"

and of course, if I need the cost of cars, I need to do this:

console.log(meh[0][1]) //Shows 27

Now I have a line - Keys such as cars, bikesorskates

But I can't figure it out: how do I access their respective values?

meh["cars"] returns undefined, because, as I understand it, it cannot find a description outside each object.

I can do meh[0]["cars"], but he defeats the point, as the position of cars can change.

How do I access the value of something with their key?

thank.

+3
5

, :

meh = {
  'cars': 27,
  'bikes': 85,
  'skates': 4
};

,

meh["cars"] //will give you 27

, , , - jQuery.each temp.

+4

var meh={"cars" :27 , "bikes" :85, "skates" :4};

alert(meh['cars']); //27
+8

:

var meh = {
    "cars":   27,
    "bikes":  85,
    "skates": 4
};

$.each():

$.each(meh, function (key, value) {
    // key == "cars" and value == 27, etc.
});

:

meh.cars

:

meh["cars"]

, .

+3

You have a data structure in the array, so you always need to access the syntax of the array, for example. [0] [1]. Arrays in JavaScript are not associative. You can write a helper function that iterates around the array, looking for the key you specified and returning the value back. Or you can change your data structure as objects that support key searches.

0
source

If you cannot change the object, you can create a map to simplify index management. For instance.

map = {
  'cars': 0,
  'bikes': 1,
  'skates': 2
};

Then you can do:

alert(meh[map['cars']][1]);
0
source

All Articles