Node.js:检查对象中是否缺少属性

Node.js : check if a property is absent from object

本文关键字:是否 属性 对象 js 检查 Node      更新时间:2023-10-15

我正在检查obj中是否不存在属性'classes'(未继承),所有这些都给了我真正的

(typeof obj['lessons'] == undefined)

(!(obj.hasOwnProperty('lessons')))

(!(hasOwnProperty.call(obj,'lessons')))

(!(_.has(obj, 'lessons')))

(!Object.prototype.hasOwnProperty.call(obj, 'lessons’))

但是当我使用(key in obj)打印键时,该属性存在于对象中。我不想用它,因为它很慢,而且我的物体很大。

我在stackoverflow上发现了这个,但我不明白它想做什么,也不知道如何将它与node.js.一起使用

我也想知道上面提到的使用hasOwnProperty的方法有什么不同。

编辑 添加代码

我的代码是:

console.log("LS:",JSON.stringify(obj)) ;
if (typeof obj['lessons'] == undefined)
    console.log('typeof undefined');
else {console.log('typeof not undefined');}
if (!(obj.hasOwnProperty('lessons')))
    console.log('hasOwnProperty: false');
else {console.log('hasOwnProperty not undefined');}
if (!(hasOwnProperty.call(obj,'lessons')))
    console.log('hasOwnProperty.call');
else {console.log('hasOwnProperty.call not undefined');}
if (!(_.has(obj, 'lessons')))
    console.log('_.hash');
else {console.log('_has not undefined');}
if (!(_.has(obj, 'lessons')))
    {obj['lessons'] = {"levels": []};}
else
    {console.log("has lesson level ");}
console.log("Lesson ", JSON.stringify(obj.lessons));

我得到的输出是:

LS: {"_id":"N9zmznzAWx","time":"1970-01-01T00:33:36.000Z","lessons":{"levels":["abc"]}}
typeof not undefined
hasOwnProperty: false
hasOwnProperty.call
_.hash
Lesson {"levels":[]}

其他情况相同。。

解决方案当我使用JSON.parse(JSON.stringfy(obj))而不是obj.时,它就起作用了

您的检查不起作用,因为Mongoose文档对象不使用简单的对象属性来公开它们的字段。

相反,您可以使用Document#get方法(将obj重命名为doc):

var isMissing = (doc.get('lessons') === undefined);

或者,您可以通过在文档上调用toObject()来创建一个纯JS对象,然后在该对象上使用hasOwnProperty

var obj = doc.toObject();
var isMissing = !obj.hasOwnProperty('lessons');

以下是我作为示例编写的一个函数,用于测试您在问题中列出的三种方法:

function check(obj) {
  if (!obj.hasOwnProperty("lessons")) {
    console.log('nope');
  }  
  if (!_.has(obj, 'lessons')) {
    console.log('nope');
  }  
  if (!obj.lessons) {
    console.log('nope');
  }
}

这里是JSBIN,它在两个对象上运行函数,一个有"课程",另一个没有:

JsBIN 示例

typeof返回字符串

var obj = {};
console.log(typeof (typeof obj.lessons));

https://jsfiddle.net/0ar2ku7v/

所以你必须这样比较:

if (typeof obj.lessons === 'undefined')
  console.log('nope');