Retrieve by value from an Object?
This must be a duplicate, but I've been Googling "retrieve by value from object javascrip开发者_如何学Ct" and "javascript lookup object by value" and every variant and got nowhere, so apologies and here goes.
Say I have a JavaScript object like this:
var options = {"ford": "red", "citroen": "blue"};
How do I do look up value blue
to get citroen
back?
There's always the 'write your own function' route, I guess:
function returnbyValue(options, v):
for (var prop in options) {
if (options.hasOwnProperty(v)) {
if (options[prop] === v) {
return prop;
}
}
}
return null;
but does JavaScript have anything inbuilt, or is there a neater way to do this?
The property of an object can be accessed just like an associative array! This worked like a charm!
var obj = {
'key': 'val'
};
alert( obj['key'] );
Alternatively, if you wish to use a method you can create a prototype method.
Object.prototype.getPropertyByString = function( str ) {
return this[str];
};
alert( obj.getPropertyByString( 'key' ) );
Edit: Wow I just noticed I failed to answer your question, my apologies! Allow me to get a second chance.
There is no built in function, but my script below works!
var obj = {
'key': 'val'
};
Object.prototype.getKeyByValue = function( object ) {
for(var key in this) {
if(this.key === object) {
return key;
}
}
return null;
};
alert( obj.getKeyByValue( 'val' ) );
It loops through the object and returns the key if it matches a value. This wil work, no matter if the value is an int, string, object, anything. This is because I've used the strict equal comparison ("===") which also checks if the object type is the same.
Also, please note that checking if the property exists is silly if you're looping through all keys of the object anyway. Obviously, when you're looping through all keys, they exist.
There is no such built-in method. And your own function looks good to me. I can't figure out any improvement of it.
精彩评论