zac
zac

Reputation: 4918

How to to use find with Object.entries()?

I have object contain these data

{
    'c':'d',
    'd':'a',
    'e':'f',
}

I am trying to use the array find() like this

let found = Object.entries(myobject).find(item => item['d'] == 'a');

but I get undefined for found value so how I should write this ?

Upvotes: 9

Views: 15359

Answers (1)

diralik
diralik

Reputation: 7236

Object.entries() returns array of pairs, where the first element of each pair is key, and the second element is value. So the callback in .find() will receive pair as argument, and then you can check its key (pair[0]) and value (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);


Alternatively, you can use array destructuring in function parameter:

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

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

console.log(found);

Upvotes: 24

Related Questions