gpt4 book ai didi

javascript - 如何检查对象的属性值?

转载 作者:行者123 更新时间:2023-11-28 14:14:26 25 4
gpt4 key购买 nike

我需要查找属性在对象中具有特定值的次数。

对象:

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

我需要查找有多少在线值为 true

到目前为止我尝试过的:

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

最佳答案

我会减少对象的Object.values,当online为true时增加累加器:

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

要修复现有代码,请将测试更改为 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));

关于javascript - 如何检查对象的属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58154735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com