Baptiste F.
Baptiste F.

Reputation: 139

How to get first true value of an object and return the corresponding key?

I have an object as :

var myObj = {called: false, invited: true, interviewed: false, offer: false}

How can I find the first value that is true and then return the corresponding key ?

I want to create a function that, given an object that is always the same structure, returns me the key of the first true value.

Upvotes: 1

Views: 4049

Answers (4)

Ramkumar Khubchandani
Ramkumar Khubchandani

Reputation: 137

Let me try to make more simpler.

const myObj = {called: false, invited: true, interviewed: false, offer: false};

console.log(Object.keys(myObj).find(key => myObj[key])) // Output: invited

Upvotes: 2

mhlavacka
mhlavacka

Reputation: 701

Here is a simpler solution to the question

const myObj = {called: false, invited: true, interviewed: false, offer: false};


const getFirstTruthyItem = (obj) => Object.keys(obj).find((i) => obj[i] === true);

console.log(getFirstTruthyItem(myObj));

Upvotes: 3

Vasyl Butov
Vasyl Butov

Reputation: 474

const myObj = {called: false, invited: true, interviewed: false, offer: false};

const getTrueKey = obj => {
  for (const key in obj) {
    if (obj[key]) return key;
  };
  return undefined;
};

console.log(getTrueKey(myObj));

Upvotes: 1

Dominik Matis
Dominik Matis

Reputation: 2146

for(let key in myObj) {
    if(myObj[key]) return key;
}

Upvotes: 1

Related Questions