1

I have a list:

var lt = {
  "part1" : "p1",
  "part2" : "p2",
  . (another key/value)
  . (another key/value)
  . (another key/value)
  . (another key/value)
}

and a variable

var myVar = "part2";

I want if myVar equal to the lt I want the variable z take the value p2 of lt. I have this:

for (var i = 0; i < lt.length; i++) {
    if (myVar === lt[i]) {
      z = lt.[i]
    }
}

However when I test it chrome console the var lt return undifined

Ster32
  • 415
  • 4
  • 10

2 Answers2

2

A dict is not an array. lt.length would returns undefined.

First test if lt[myVar] exists and then copy the value into z:

var lt = {
   "part1" : "p1",
   "part2" : "p2",
   "part3" : "p3"
}

var myVar = "part2";
var z;

if(typeof lt[myVar] !== "undefined"){
   z = lt[myVar];
}

console.log(z)
---> "p2"

or simply:

if(myVar in lt){
  z = lt[myVar];
}

see: http://jsfiddle.net/55fmggL9/4/

Below the Radar
  • 7,321
  • 11
  • 63
  • 142
1
for (var i in lt) {
    if (myVar === i) {
      z = lt[i]
    }
}
overburn
  • 1,194
  • 9
  • 27