简体   繁体   English

如何仅打印出真实的对象值?

[英]How to print out only object values that are true?

I am learning Javascript, and am making a simple user verification object. 我正在学习Javascript,并且正在制作一个简单的用户验证对象。 I need a function that will console.log only users who have "isVerified" set to true. 我需要一个将console.log仅将“ isVerified”设置为true的用户使用的函数。

I have tried numerous ways including loops and if statements. 我尝试了许多方法,包括循环和if语句。 The function name is "showVerified" below. 函数名称在下面是“ showVerified”。

var person = {
    info: [],
    displayPerson: function() {
        console.log('People', this.info);
    },
    addPerson: function(age, firstName, lastName) {
        this.info.push({
            age: age,
            firstName: firstName,
            lastName: lastName,
            isVerified: false
        });
        this.displayPerson();
    },
    deletePerson: function(position) {
        this.info.splice(position, 1);
        this.displayPerson();
    },
    verifyPerson: function(position) {
        this.info[position].isVerified = true;
        this.info[position].firstName = this.info[position].firstName.toUpperCase();
        this.displayPerson();
    },
    showVerified: function() {
        for (var key in this.info) {
            if (this.info.isVerified = true) {
                console.log(this.info.isVerified[key]);
            }
        }
    }
}

What I want to happen when running showVerified on my person object, is for it to print out ONLY the age, first name, and last name of any person who is verified. 我要在我的人员对象上运行showVerified时发生的情况是,它仅打印出已验证人员的年龄,名字和姓氏。

I suggest trying to change the way you're naming your properties, so the code is a bit clearer. 我建议尝试更改命名属性的方式,这样代码就更清晰了。 Try 尝试

showVerified: function() {
        this.info.filter(x => x.isVerified).forEach(v => console.log(v))
    }

if you don't want to use filter, you can try this as well 如果您不想使用过滤器,也可以尝试使用

this.info.forEach(person => {
   if(person.isVerified){
   console.log(person);
   }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM