卡住了嵌套数组中的元素

时间:2018-07-26 08:12:43

标签: javascript

我有此功能

  Meteor.robot.find({}, { _id: 1 }).forEach(function (robot) { x.push(robot.emails) })

将显示:

 [ { address: 'robot1@rob.fr', working: false } ],
I20180725-16:58:32.924(2)?   [ { address: 'rob2@rob.com', working: true } ],
I20180725-16:58:32.924(2)?   [ { address: 'ROB4@rob.fr', working: false } ],
I20180725-16:58:32.924(2)?   [ { address: 'rob5@rob.com', working: false } ]
 ]

humans.json

    {
        "_id": "22YAE7bEXdST9MyrZ",
        "createdAt": {
            "$date": "2016-11-22T15:09:25.968Z"
        },
        "abilities": {
            "power": {
            "mana":78,
            "chakra":0
            "energy":60
}
        },
        "emails": [
            {
                "address": "Rob6@rob.com",
                "working": false
            }
        ],
        "roles": [
           "killing":true
]
    }

我只想获取以大写字母开头的地址,而不是address + working属性。像这样。

['ROB4@rob.fr']

3 个答案:

答案 0 :(得分:0)

如果只是获取地址,只需通过循环访问电子邮件中的address属性。

Meteor.robot.find({}, { _id: 1 }).forEach(function (robot) {
    var addresses = [];
    robot.emails.forEach(function(element) {
        if (typeof element.address != undefined) {
            addresses[] = element;
        }
    });
    x.push(addresses);
})

答案 1 :(得分:0)

这应该有效。

Meteor.robot.find({''}, { _id: 1 }).forEach(function (robot) { 
if(robot.emails){
    for(var i = 0; i<robot.emails.length; i++){
       var email = robot.emails[i];
       var emailAddress = email.address;
       if(emailAddress && emailAddress.charCodeAt(0) >= 65 && emailAddress.charCodeAt(0) <= 90){
             // pushing only when email address starts with Uppercase.
             x.push(email.address);
        }
    }
});

答案 2 :(得分:-1)

因此,由于robot.emails是一个数组,所以简单的解决方案是遍历emails数组,只返回地址,而不返回working属性。

要实现此目的,例如,您可以使用.map

Meteor.robot.find({''}, {
    _id: 1
}).forEach(function (robot) {
    // only returns the address part of the robot object
    x.push(robot.emails.map(email => { return { address: email.address }; }))
});