Object.keys and Array.prototype.find
We can use the Object.keys
method to return an array of non-inherited string keys in an object.
And we can use the JavaScript array’s find
method to return the first instance of something that meets the given condition in an array.
For instance, we can write:
const object = {
a: 1,
b: 2,
c: 3
}
const value = 2;
const key = Object.keys(object).find(key => object[key] === value);
console.log(key)
We have the object
object that we want to search for the key in.
And value
is the value of the key that we want to search for.
We get all the keys of object
with Object.kets
.
Then we call find
with a callback that returns object[key] === value
.
key
is the object
key being iterated through to find the key name for the given value
.
Therefore, we should see that key
is 'b'
from the console log.
Object.keys and Array.prototype.filter
We can replace the find
with filter
and destructure the result from the array returned by filter
.
For instance, we can write:
const object = {
a: 1,
b: 2,
c: 3
}
const value = 2;
const [key] = Object.keys(object).filter(key => object[key] === value);
console.log(key)
And we get the same result for key
as in the previous example.
Object.entries and Array.prototype.find
We can use the Object.entries
method to return an array of arrays of key-value pairs of an object.
Therefore, we can use the returned array to find the key of the object with the given value.
For instance, we can write:
const object = {
a: 1,
b: 2,
c: 3
}
const value = 2;
const [key] = Object.entries(object).find(([, val]) => val === value);
console.log(key)
We call find
with a callback that has the parameter with the val
variable destrutured from the parameter.
val
has the value of the in the key-value pair array.
So when we return val === value
, we return the same boolean expression as the first example.
From the returned result of find
, we can get the key of from the returned key-value pair by destructuring it.
And so we get the same value of key
logged in the console log.