首页 > 解决方案 > 从多个其他对象中的 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);
            }
        });

谢谢

标签: javascriptarraysjsonobject

解决方案


我稍微扩展了您的示例对象并使用简单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}


推荐阅读