【问题标题】:onChange to check all property of object exist and is not undefined or empty stringonChange 检查对象的所有属性是否存在且不是未定义或空字符串
【发布时间】:2017-09-19 03:29:42
【问题描述】:

这是一种非常常见的用法,您必须检查是否所有字段都已填写。我使用 react onChange 并应用 e.target.name 作为我的对象的键。

像我一样console.log(this.state.user);我会得到

user : {
    name:"something",
    age:1
}

但是如何检查所有内容是否为空或不为空?我像user.name != undefined 一样手动检查,但我的密钥超过 10。有没有更好的 lodash 方法来做到这一点?

我这样设置状态

const user = this.state.user;
user[field] = event.target.value;

this.setState({
    user
});

【问题讨论】:

    标签: javascript reactjs ecmascript-6 lodash


    【解决方案1】:

    您可以迭代对象的值并使用reduce 方法。

    const allExist = Object.values(this.state.user)
      .reduce(function(accumulator, current){
       return accumulator && !!current
      }, true);
    

    const user = {
      name:"something",
      age:1
    }
    
    const allExist = Object.keys(user)
      .reduce(function(accumulator, current){
       return accumulator && !!current
      }, true);
      
    console.log(allExist);

    【讨论】:

    • 是真的,reduce的第二个参数需要吗?
    • 这是初始值。如果未提供初始值,则将使用数组中的第一个元素。我使用它是因为它确保我总是得到一个布尔值作为输出,即使对象中有一个属性。
    • 您得到错误或错误结果?我可以看看你的完整 user 对象吗?
    【解决方案2】:

    您可以使用Object.keys 方法 - 循环生成的数组并检查每个键是否具有有效值:

    const user = {
      name: "Tom",
      age: 28,
      address: null,
      occupation: "Programmer",
      interest: "JavaScript",
      dob: undefined
    }
    
    const keys = Object.keys(user);
    for (let i = 0; i < keys.length; i++) {
      if (user[keys[i]] == null) {
        console.log(`${keys[i]} needs a value`);
      }
    }

    【讨论】:

      猜你喜欢
      • 2015-06-04
      • 1970-01-01
      • 2014-05-06
      • 2011-08-15
      • 2011-04-05
      • 1970-01-01
      • 2019-06-27
      • 2015-09-27
      • 2017-12-26
      相关资源
      最近更新 更多