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.
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.
- 1 What have YOU tried so far? Where did you get stuck? – MrSmith42 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. – JardonS Commented Aug 2, 2019 at 14:04
- Related: stackoverflow./questions/5525795/… – Moritz Roessler Commented Aug 2, 2019 at 14:08
4 Answers
Reset to default 3Here 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));
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
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));
for(let key in myObj) {
if(myObj[key]) return key;
}