0

I've been given a function with a dictionary like this:

  var letters =  {
    "A": "Alpha",  "B": "Bravo",   "C": "Charlie",
    "D": "Delta",  "E": "Echo",    "F": "Foxtrot",
    "G": "Golf",   "H": "Hotel",   "I": "India",
    "J": "Juliett","K": "Kilo",    "L": "Lima",
    "M": "Mike",   "N": "November","O": "Oscar",
    "P": "Papa",   "Q": "Quebec",  "R": "Romeo",
    "S": "Sierra", "T": "Tango",   "U": "Uniform",
    "V": "Victor", "W": "Whiskey", "X": "X-ray",
    "Y": "Yankee", "Z": "Zulu"
  }

I need to replace letters in the strings passed in with their corresponding dictionary word. How can I access the dictionary elements in an object like this?

user137717
  • 2,005
  • 4
  • 25
  • 48
  • You can use for....in loop – Bhojendra Rauniyar Dec 26 '14 at 03:59
  • Have you made an attempt at solving this yet? – j08691 Dec 26 '14 at 04:01
  • @j08691 yea, I tried breaking the passed in strings into arrays, looping over each letter and using an array like syntax to access the words like word[i] = letters[word[i]]. – user137717 Dec 26 '14 at 04:03
  • Please read up on basic JS. Any tutorial will talk early on about how to retrieve properties from objects, using the `object[property]` syntax. –  Dec 26 '14 at 04:15
  • I may have been too hasty in asking this. I was using the right syntax, but didn't convert my data to the proper types stored in the dictionary. apologies. – user137717 Dec 26 '14 at 04:18

1 Answers1

0

If I understand your question correctly, this is what you need to do.

var letters =  {
    "A": "Alpha",  "B": "Bravo",   "C": "Charlie",
    "D": "Delta",  "E": "Echo",    "F": "Foxtrot",
    "G": "Golf",   "H": "Hotel",   "I": "India",
    "J": "Juliett","K": "Kilo",    "L": "Lima",
    "M": "Mike",   "N": "November","O": "Oscar",
    "P": "Papa",   "Q": "Quebec",  "R": "Romeo",
    "S": "Sierra", "T": "Tango",   "U": "Uniform",
    "V": "Victor", "W": "Whiskey", "X": "X-ray",
    "Y": "Yankee", "Z": "Zulu"
}

function findWord(search_value) {

    var outputWord="";
    for (var i=0; i<search_value.length; i++) {
         var letter = search_value.charAt(i);

         for (var key in letters) {
           if (letters.hasOwnProperty(key)) {
              if (key == letter) {
                console.log("outputWord-",outputWord+=letters[key]);
              }
           }
       }
    }
 }

findWord("ABCDD");

Output: AlphaBravoCharlieDeltaDelta

Pramod Karandikar
  • 5,289
  • 7
  • 43
  • 68