最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get first true value of an object and return the corresponding key? - Stack Overflow

programmeradmin3浏览0评论

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.

Share Improve this question asked Aug 2, 2019 at 13:57 Baptiste F.Baptiste F. 1393 silver badges15 bronze badges 3
  • 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
Add a ment  | 

4 Answers 4

Reset to default 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));

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;
}
发布评论

评论列表(0)

  1. 暂无评论