Reputation: 139
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
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
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
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