1

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.

3
  • 1
    What have YOU tried so far? Where did you get stuck? Commented Aug 2, 2019 at 14:00
  • 3
    Do you know that the property collection is not ordered ? If you are expecting a rules of priority there, it will not works. Commented Aug 2, 2019 at 14:04
  • Related: stackoverflow.com/questions/5525795/… Commented Aug 2, 2019 at 14:08

4 Answers 4

3

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));

Sign up to request clarification or add additional context in comments.

1 Comment

In JavaScript, it's bit misleading to name the function getFirstTruthyItem as you're strictly comparing with the keyword true. The context being that "truthy" has a wider meaning than === true in JavaScript.
2

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

Comments

1

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));

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.