Node.js:检查对象

时间:2016-04-01 03:22:21

标签: javascript node.js mongoose

我正在检查一个属性的课程' obj中不存在(未继承) 所有这些都给了我真实的

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

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

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

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

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

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

我在stackoverflow上找到this,但我不明白它在尝试做什么或如何在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.stringify(obj))而不是obj时,它可以工作。

3 个答案:

答案 0 :(得分:1)

您的检查无效,因为Mongoose文档对象不使用简单对象属性来公开其字段。

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

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

或者您可以通过调用文档上的toObject()从文档中创建一个普通的JS对象,然后在其上使用hasOwnProperty

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

答案 1 :(得分:0)

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

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

这是JSBIN,它在两个对象上运行该功能,其中一个带有“课程”和#39;一个没有:

Example JsBIN

答案 2 :(得分:0)

typeof返回一个字符串

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

https://jsfiddle.net/0ar2ku7v/

所以你必须比较它:

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