Videos
function getKeyByValue(object, value) {
return Object.keys(object).find(key => object[key] === value);
}
ES6, no prototype mutations or external libraries.
Example,
function getKeyByValue(object, value) {
return Object.keys(object).find(key => object[key] === value);
}
const map = {"first" : "1", "second" : "2"};
console.log(getKeyByValue(map,"2"));
No standard method available. You need to iterate and you can create a simple helper:
Object.prototype.getKeyByValue = function( value ) {
for( var prop in this ) {
if( this.hasOwnProperty( prop ) ) {
if( this[ prop ] === value )
return prop;
}
}
}
var test = {
key1: 42,
key2: 'foo'
};
test.getKeyByValue( 42 ); // returns 'key1'
One word of caution: Even if the above works, its generally a bad idea to extend any host or native object's .prototype. I did it here because it fits the issue very well. Anyway, you should probably use this function outside the .prototype and pass the object into it instead.
Do you use Object.keys often?
Can you explain what's going on in this code what would be the key, index.
At first I was still thing they was object not arrays because that's what they looked like. I know the key was username1/2/3/ and the value is ben/kevin/deku but they don't have index and removing index from the parameters changed nothing, but arrays have index but not keys. from the cosole.log to get the key we console.log key, and to get the value its obj[key] but why?
I tried console.log(Object.keys(obj)) but that mad it more confusing because now the names(values) where gone and it was just an array of the username(keys)
let obj ={
username1: "ben",
username2: "kevin",
username3: "deku"
}
Object.keys(obj).forEach((key, index) =>{
console.log(key, obj[key]);
})
// username1 ben
// username2 kevin
// username3 deku
let obj ={
username1: "ben",
username2: "kevin",
username3: "deku"
}
Object.keys(obj).forEach((key) =>{
console.log(key, obj[key]);
})
// username1 ben
// username2 kevin
// username3 deku
let obj ={
username1: "ben",
username2: "kevin",
username3: "deku"
}
Object.keys(obj).forEach((key, index) =>{
console.log(obj[key]);
})
// ben
// kevin
// deku
let obj ={
username1: "ben",
username2: "kevin",
username3: "deku"
}
Object.keys(obj).forEach((key) =>{
console.log(key);
})
// username1
// username2
// username3Use Object.keys:
var foo = {
'alpha': 'puffin',
'beta': 'beagle'
};
var keys = Object.keys(foo);
console.log(keys) // ['alpha', 'beta']
// (or maybe some other order, keys are unordered).
This is an ES5 feature. This means it works in all modern browsers but will not work in legacy browsers.
The ES5-shim has a implementation of Object.keys you can steal
You can use jQuery's $.map.
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' },
keys = $.map(foo, function(v, i){
return i;
});