【问题标题】:How can I access a specific attribute of an object that is within an array of objects? [duplicate]如何访问对象数组中对象的特定属性? [复制]
【发布时间】:2022-01-10 18:33:15
【问题描述】:

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

例如 多少在线(用户)返回 2 this 对象的对象:

    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) {

  }

我该怎么做?

【问题讨论】:

  • 你可以遍历一个对象的所有属性,虽然最好有一个对象数组
  • Object.values(users).filter(user => user.online).length

标签: javascript


【解决方案1】:

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

在从对象中获取值后使用array.filter 过滤到仅在线用户,然后对该数组进行计数。此方法采用回调函数,并且是更“javascripty”的方式。

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

【讨论】:

  • OP 没有数组,它们有一个带有属性的对象
【解决方案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) {
  let count = 0;
  for (const { online } of Object.values(users)) {
    if (online) count += 1;
  }
  return count;
}

console.log(howmanyOnline(users));

【讨论】:

    【解决方案3】:

    这应该通过使用 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))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 2016-02-26
      • 2018-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多