动态处理嵌套对象

时间:2019-04-26 07:16:44

标签: javascript object

我需要计算此嵌套对象中的在线用户数,然后返回总数。

我已经尝试过这段代码,但是我有点迷路了

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

function countOnline(obj) {
    let c = 0;
    for (let i in obj) {
        for (let j in i) {
            if (j.online === true) {
                c++;
            }
        }
    }
    return c;

}

它返回0

3 个答案:

答案 0 :(得分:1)

最好使用reduce-遍历对象的Object.values,然后将.online的值添加到累加器中:

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

要修复原始代码,只需要在users的每个属性上循环一次 ,而不仅是users 和以及每个嵌套属性(您只需要online属性)。您还需要访问obj[i],因为i属性,而不是值:

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

function countOnline(obj) {

  let c = 0;
  for (let i in obj) {
    if (obj[i].online === true) {
      c++;
    }
  }
  return c;
}
console.log(countOnline(users));

答案 1 :(得分:0)

您只需要在users[i].online条件下执行if。不需要嵌套的for

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

function countOnline(obj) {

  let c = 0;
  for (let i in obj) {
    if (users[i].online) {
      c++;
    }
  }
  return c;

}

console.log(countOnline(users));

您还可以将代码和逻辑缩短为:

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

function countOnline(obj) {
 var c = 0;
 Object.keys(obj).forEach((key) => obj[key].online ? ++c: null);
 return c;
}

console.log(countOnline(users));

答案 2 :(得分:0)

您可以使用online的所有用户Object.values()filter获得所有值。

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

const count = Object.values(users).filter(a => a.online).length;

console.log(count)

但是,我认为您最好使用users数组,而不要使用其名称作为对象的键。如果有多个同名用户,则此对象方法将无效