I have a quite simple JavaScript object, which I use as an associative array. Is there a simple function allowing me to get the key for a value, or do I have to iterate the object and find it out manually?
To get an object's key by it's value:Call the Object. keys() method to get an array of the object's keys. Use the find() method to find the key that corresponds to the value. The find method will return the first key that satisfies the condition.
Use object. keys(objectName) method to get access to all the keys of object.
In order to get a key-value pair from a KiiObject, call the get() method of the KiiObject class. Specify the key for the value to get as the argument of the get() method.
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With