如何访问数组对象中特定对象的属性?

3

我有一个名为“howmanyOnline”的函数,它接收一个对象users。每个用户都有一个属性online,它是一个布尔值。该函数应该返回属性online等于true的用户数量。

例如: How many Online (users)返回2。 这是对象的对象:

    let users = {
      Victor: {
              age: 33,
             online: true
     },
      joan: {
         age: 25,
         online: true
      },
     frank: {
         age: 25,
         online: false
     },
     Emy: {
          age: 24,
          online: false
       }
  }; 

   

    function howmanyOnline(users) {

  }

我怎样才能做到这一点?


你可以遍历一个对象的所有属性,但最好是使用对象数组。 - UnholySheep
1
Object.values(users).filter(user => user.online).length - user5734311
3个回答

1

有很多方法可以做到这一点,但最常见的是以下两种之一:

在获取对象中的值后使用 array.filter 过滤仅保留在线用户,然后取该数组的计数。此方法需要回调函数,并且是更加“javascript”的方法。

const values = {one: {a: 1}, two: {a: 2}, three: {a: 3}};
const arr = Object.values(values);
// filter down to only the elements which a value >= 2 under key 'a'
const filtered = arr.filter(obj => obj.a >= 2);
filtered.length; // 2

首先将一个变量初始化为0,然后使用map或其他方式遍历对象,并对每个在线用户将变量加1。

let count = 0;
const values = {one: {a: 1}, two: {a: 2}, three: {a: 3}};
// check if the value under key 'a' is >= 2, if so add 1 to count,
// otherwise add 0
for(value in values){count += values[value]['a'] >= 2 ? 1 : 0};
count; // 2


2
OP没有一个数组,他们有一个带有属性的对象。 - UnholySheep

0

这应该可以通过使用 for 循环来获取在线值,然后使用 if 语句检查它是否为真来实现。

let users = {
              Victor: {
                      age: 33,
                     online: true
             },
              joan: {
                 age: 25,
                 online: true
              },
             frank: {
                 age: 25,
                 online: false
             },
             Emy: {
                  age: 24,
                  online: false
               }
          }; 
    let number =0
           

            function howmanyOnline(users) {
        for(let value of Object.values(users)){
         if(value.online)
         number++
        }
        return number
          }
          console.log(howmanyOnline(users))


0

let users = {
  Victor: {
    age: 33,
    online: true
  },
  joan: {
    age: 25,
    online: true
  },
  frank: {
    age: 25,
    online: false
  },
  Emy: {
    age: 24,
    online: false
  }
};

function howmanyOnline(users) {
  let count = 0;
  for (const { online } of Object.values(users)) {
    if (online) count += 1;
  }
  return count;
}

console.log(howmanyOnline(users));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接