验证javascript对象中字段的更好方法

时间:2019-05-07 10:59:26

标签: javascript arrays

我想验证对象,以使该对象不为null且该对象中的少数字段不为空。

例如,考虑以下对象:

address ={
    block : '2134',
    street : 'berly street',
    county : 'someCountry'
    postal : '876546'
}

我正在使用es6。我找到了解决方法,using lodash

我想用普通的JS做到这一点。 请让我知道是否有比以下更好的方法:

 const isValidAddress = (address) => {

      const addressFields = ['block', 'county', 'postal', 'street'];
      return addressFields.every((element) => address[element] && address[element].length > 0);
};

1 个答案:

答案 0 :(得分:2)

您可以尝试像这样用Array.prototype.every检查每个值。

const invalidAdress ={
    block: '',
    street: 'berly street',
    county: 'someCountry',
    postal: '876546'
};

const validAdress ={
    block: '1234',
    street: 'berly street',
    county: 'someCountry',
    postal: '876546'
};

// .every will return true if and only if every property in the object is a truthy value
const isValidAddress = (address) => Object.keys(address).every(x => address[x]);

console.log(isValidAddress(invalidAdress));
console.log(isValidAddress(validAdress));