如何在 Object.entries() 中使用 find?

Wel*_*Wel 1 typescript

我有对象包含这些数据

{
    'c':'d',
    'd':'a',
    'e':'f',
}
Run Code Online (Sandbox Code Playgroud)

我试图使用数组find()像这样

let found = Object.entries(myobject).find(item => item['d'] == 'a');
Run Code Online (Sandbox Code Playgroud)

但我的found价值未定义,所以我应该怎么写?

dir*_*lik 13

Object.entries()返回对的数组,其中每对的第一个元素是key,第二个元素是value。所以回调 in.find()pair作为参数接收,然后您可以检查其键 ( pair[0]) 和值 ( pair[1]):

const myObject = {
  'c': 'd',
  'd': 'a',
  'e': 'f',
}

const found = Object.entries(myObject)
  .find(pair => pair[0] === 'd' && pair[1] === 'a');

console.log(found);
Run Code Online (Sandbox Code Playgroud)


或者,您可以在函数参数中使用数组解构

const myObject = {
  'c': 'd',
  'd': 'a',
  'e': 'f',
}

const found = Object.entries(myObject)
  .find(([key, value]) => key === 'd' && value === 'a');

console.log(found);
Run Code Online (Sandbox Code Playgroud)