确定对象何时只具有某些属性

determine when an object only has certain properties

本文关键字:属性 对象 何时      更新时间:2023-09-26

我正在创建一个对象,我使用它通过ajax将数据传回服务器。

属性是根据服务器更新应该包含的数据添加到对象的。其中两个属性在每个更新对象FruitIDPeachID

但是,当一个update对象为ajax调用呈现自己并且只有这两个属性时,我想取消调用。

如何确定一个对象只包含某些属性?

谢谢你的建议。

var obj = {a:"property 1",b:"property 2"} // Or whatever object you want to check.
if(Object.keys(obj).length == 2     // If the object only has 2 keys,
    && obj["FruitID"]   // And FruitID exists as property of the object,
    && obj["PeachID"]){ // And PeachID exists as property of the object,
    // The object only contains FruitID & PeachID;
}

或者将其封装在函数中:

function isBaseObject(obj){
    return !!(Object.keys(obj).length == 2 && obj["FruitID"] && obj["PeachID"]); // !! to cast the output to a boolean
}
isBaseObject({FruitID:"property 1",PeachID:"property 2"})
//true
isBaseObject({FruitID:"property 1",PeachID:"property 2", a:1})
//false
isBaseObject({a:1})
//false

听起来你想使用hasOwnProperty

if (myObject.hasOwnProperty("FruitID")) { ... }

另一个选择可能是使用Object.keys,但它只支持在现代浏览器。不过,比较一下是否只存在这些属性会更容易。

您需要使用hasOwnProperty

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

o = new Object();
o.prop = 'exists';
o.hasOwnProperty('prop');   //returns true