views:

65

answers:

1

I have this JSON for smilies list

var smiliesList = {
"sm-1":":)",
"sm-2":":(",
"sm-3":";)"
}

There are lots more than 3 actually.

In other part of the code I use smiliesList["sm-1"] to get ":)". However, I want to get the opposite now. I have a text string, I want to go through the whole smiliesList and replace ":)" with "sm-1" and so on. That means using smiliesList[":)"] to get "sm-1".

So there are 2 parts: 1. How to go through the whole JSON? 2. How to get the opposite variable string?

Now is there a way to do this? Any workaround? Thanks

A: 

You can iterate over object properties, using the for...in statement:

function getKeyByValue (obj, val) {
  for (var key in obj) {
    if (obj.hasOwnProperty(key) && obj[key] == val) {
      return key;
    }
  }
}

getKeyByValue (smiliesList, ":)"); // sm-1

You have to be careful when using for...in because it iterates through all of the members which were inherited through the prototype chain, for that is always recommended to check if the object has the property defined direcly, by using the hasOwnProperty function.

CMS