使用 JavaScript 通过对象的值获取对象的键

在 JavaScript 中通过对象的值获取对象的键

Get an Object’s Key by its Value using JavaScript

通过对象的值获取对象的键:

  1. 调用该Object.keys()方法以获取对象键的数组。
  2. 使用该find()方法找到与值对应的键。
  3. find方法将返回满足条件的第一个键。
索引.js
function getObjKey(obj, value) { return Object.keys(obj).find(key => obj[key] === value); } const obj = {country: 'Chile', city: 'Santiago'}; console.log(getObjKey(obj, 'Chile')); // 👉️ "country"

我们使用
Object.keys
方法获取包含对象键的数组。

索引.js
const obj = {country: 'Chile', city: 'Santiago'}; console.log(Object.keys(obj)); // 👉️ ['country', 'city']

然后,我们

在键数组上调用
Array.find方法。

The function we passed to the find() method gets called with each element (key) in the array until it returns a truthy value or iterates over the entire array.

On each iteration, we use the key to access the object’s value and compare it to
the supplied value.

If equality check succeeds, the find method returns the corresponding key and
short-circuits.

If the equality check never returns true, the find method returns
undefined.

index.js
function getObjKey(obj, value) { return Object.keys(obj).find(key => obj[key] === value); } const obj = {country: 'Chile', city: 'Santiago'}; console.log(getObjKey(obj, 'DoesNotExist')); // 👉️ undefined
The find method returns the first element that satisfies the testing function. If you have multiple keys with the same value, you would get the name of the first key.
index.js
function getObjKey(obj, value) { return Object.keys(obj).find(key => obj[key] === value); } const obj = {city1: 'Santiago', city2: 'Santiago'}; console.log(getObjKey(obj, 'Santiago')); // 👉️ "city1"

To get multiple object keys that store the same value:

  1. Call the Object.keys() method to get an array of the object’s keys.
  2. 调用Array.filter()键数组上的方法。
  3. filter()方法将返回一个包含所有匹配键的新数组。
索引.js
function getObjKeys(obj, value) { return Object.keys(obj).filter(key => obj[key] === value); } const obj = {city1: 'Santiago', city2: 'Santiago'}; // 👇️️ ["city1", "city2"] console.log(getObjKeys(obj, 'Santiago'));

通过使用
Array.filter
方法,我们得到一个包含所有满足条件的键的数组。

我们传递给filter()方法的函数会为数组中的每个键调用,并且不会在第一个真实响应时短路。