javascript - 从多个其他对象中的 Javascript 对象获取名称
问题描述
我真的很难找到这个 javascript 对象中的名称。请问有人可以帮我吗?我想要的是获取某人的名字,如果他们的“出席”状态为真,则将他们的名字推入“去”数组,如果他们的状态为假,则将他们的名字推入“不去”数组。
对象在下面,然后我到目前为止写的代码在下面。当我到达名称级别时,我不知道该怎么办,因为它们是不同的名称...
"HmS7XXPFoCQ7GmvfcCnF": {
"invitees": {
"gus": {
"attending": true,
"invitedBy": "will"
},
"margot": {
"attending": "false",
"invitedBy": "gus"
}
}
}
这是我的代码:
Object.keys(invitees).map(function(keyName, i) {
if (invitees[keyName] === true) {
//this is causing problems as the last name will be displayed as august,
inviteesGoing.push(`${keyName}, `);
} else if (invitees[keyName] === false) {
//this is causing problems as the last name will be displayed as august,
inviteesNotGoing.push(`${keyName}, `);
} else {
console.error("undetermind user status:" + keyName);
}
});
谢谢
解决方案
我稍微扩展了您的示例对象并使用简单forEach
的方法解决了您的问题。你可以试试这个:
const data = {
"invitees": {"gus": {"attending": true, "invitedBy": "will"}, "margot": {"attending": false, "invitedBy": "gus"}, "John": {"attending": true, "invitedBy": "gus"}, "doe": {"attending": true, "invitedBy": "John"}, "Alex": {"attending": false, "invitedBy": "John"}}
};
const going = [], notGoing = [];
Object.entries(data.invitees).forEach(([name, value]) => {
if (value.attending) {
going.push(name);
} else {
notGoing.push(name);
}
});
console.log('going', going);
console.log('not going', notGoing);
.as-console-wrapper{min-height: 100%!important; top: 0}
推荐阅读
- javascript - 有没有办法从可选变量中解包?
- python - 将遗留系统与 Celery 集成
- full-text-search - 两个数据库的快速全文比较
- javascript - 创建频道后找不到频道 discord.js v13
- javascript - Buddypress:还保存个人资料图片的大版本
- bash - bash 回显到文件失败并显示“没有这样的文件”
- python - Python BeautifulSoup 类查找返回无
- php - 点转移到用户错误 laravel
- python - 将 exog 变量添加到 SARIMAX 网格搜索中
- java - 如何将 SQL“select case when in”转换为 JPQL 以获得相同的结果?