1

I have a Json object in following format

MyJsonObject= {
    'Animal': ['Lion', 'Tiger', 'Elephant'],
    'Human': ['Man', 'Woman']
};

I want to get the key as return type if we pass value to function. Eg If I pass value =Man, function should return Human as return type. similarly, If I passed Tiger as value than I want to get Animal as return value.

Any help will be appreciated

taxicala
  • 21,408
  • 7
  • 37
  • 66
LilRazi
  • 690
  • 12
  • 33

2 Answers2

1

Hi the snippet bellow should work.

You can try here http://jsfiddle.net/xtdqodzk/1/

MyJsonObject= {
    'Animal': ['Lion', 'Tiger', 'Elephant'],
    'Human': ['Man', 'Woman']
};
function find(value){
    for(var prop in MyJsonObject ){
        if(MyJsonObject.hasOwnProperty(prop)){
            for(var i =0 ;i<MyJsonObject[prop].length;i++){
                if(MyJsonObject[prop][i] === value){
                    return prop;
                }
             }
        }
    }
}
alert(find('Man'));
Su4p
  • 865
  • 10
  • 24
1

You can try to modify Object prototype

Object.prototype.findKey = function(value) {
  for (var key in this) {
    if (this.hasOwnProperty(key)) {
      for (var i = 0; i < this[key].length; i++) {
        if (this[key][i] === value) {
          return key;
        }
      }
    }
  }
}

var MyJsonObject = {
    'Animal': ['Lion', 'Tiger', 'Elephant'],
    'Human': ['Man', 'Woman']
};

console.log(MyJsonObject.findKey('Man'));

The advantage of doing this way is if you have another json object you can call .findKey function on that object as well since all objects inherit functions and properties from Object.prototype object (prototypal inheritance).

tlaminator
  • 946
  • 2
  • 9
  • 23