api返回的数据中缺少一些属性,需要可靠的方法来检查属性

Some properties are missing from API's returned data, need solid way to check property

本文关键字:属性 方法 检查 数据 返回 api      更新时间:2023-09-26

我知道api团队负责向请求数据的客户端发送正确的数据。但是,我还是想知道检查property是否存在的最好方法。

// when state property is missing from the api response
myObject = {
  name : 'Scott',
  addressInfo : {
    address1 : '444 St Peter St',
    address2 : 'Apartment D',
    zipCode  : '55555'
  },
  birthDate : '20000101'
}

// or when birtdate is missing
myObject = {
  name : 'Scott',
  addressInfo : {
    address1 : '444 St Peter St',
    address2 : 'Apartment D',
    zipCode  : '55555',
    state    : 'MN'
  }
}

// when addressInfo is missing
myObject = {
  name : 'Scott',
  birthDate : '20000101'
}

下面的代码足够检查吗?

if (myObject.addressInfo !== undefined && myObject.addressInfo.state !== undefined) {
    // console.log(
}

如果您愿意使用lodash或underscore之类的库,那么测试对象中是否存在键的一种非常方便的方法是_.has方法:

var x = { "a": 1 };
_.has(x,"a"); //returns true
_.has(x,"b"); //returns false

state值可以设置为undefined,但仍是myObject的属性;尝试使用Object.hasOwnProperty(property)

var myObject = {
  name : 'Scott',
  addressInfo : {
    address1 : '444 St Peter St',
    address2 : 'Apartment D',
    zipCode  : '55555'
  },
  birthDate : '20000101'
};
console.log(myObject.addressInfo.hasOwnProperty("state"))

检查属性是否存在的正确方法:

if(myObj.hasOwnProperty(myProp)){
    alert("yes, i have that property");
}

if(myProp in myObj){
    alert("yes, i have that property");
}

从回答:检查对象属性是否存在-使用变量