简体   繁体   English

如何检查 object 的属性值?

[英]How to check the value of a property of an object?

I need to find the number of times a property has a specific value in an object.我需要找到一个属性在 object 中具有特定值的次数。

The object: object:

let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Ryan: {
    age: 19,
    online: true
  }
};

I need to find the number of how many online have the value true我需要找到多少在线有多少值为真

What I've tried so far:到目前为止我已经尝试过:

function countOnline(obj) {
  let count = 0;
    for (let user in obj) {
      if (obj.user == true) {
      count++;
      }
    }
  return count;
}

console.log(countOnline(users)); // 0
console.log(users.Ryan.online); // true


console.log(countOnline(users)); // should return 2 as the number of online: true exists twice

I'd reduce the Object.values of the object, incrementing the accumulator when online is true:我会reduce Object.values的 Object.values,当online为真时增加累加器:

 let users = { Alan: { age: 27, online: false }, Jeff: { age: 32, online: true }, Ryan: { age: 19, online: true } }; const onlineCount = Object.values(users).reduce((a, { online }) => a + online, 0); console.log(onlineCount);

To fix your existing code, change the test to obj[user].online === true (or just obj[user].online ):要修复现有代码,请将测试更改为obj[user].online === true (或只是obj[user].online ):

 let users = { Alan: { age: 27, online: false }, Jeff: { age: 32, online: true }, Ryan: { age: 19, online: true } }; function countOnline(obj) { let count = 0; for (let user in obj) { if (obj[user].online === true) { count++; } } return count; } console.log(countOnline(users));

You need to access online property of obj您需要访问obj的在线属性

if (obj[user].online == true) or if (obj[user].online)

When you do obj.user it tries to find user property on obj whose value will be undefined as we don't have any property named user on obj当您执行obj.user时,它会尝试在obj上查找user属性,其值将undefined ,因为我们在obj上没有任何名为user的属性

You can simply filter values based on online property and check length您可以简单地根据在线属性过滤值并检查长度

 let users = {Alan: {age: 27,online: false},Jeff: {age: 32,online: true},Ryan: {age: 19,online: true}}; let count = Object.values(users).filter(({ online }) => online).length console.log(count)

 let users = { Alan: { age: 27, online: false }, Jeff: { age: 32, online: true }, Ryan: { age: 19, online: true } }; let onlineUser = Object.keys(users).filter(item => users[item].online).reduce((obj, key) => { obj[key] = users[key]; return obj; }, {}); console.log("count:", Object.keys(onlineUser).length); console.log("onlineUser:", onlineUser);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM