检查对象的一个​​属性是null还是未定义

时间:2017-04-24 09:04:01

标签: javascript angularjs json

我有一个这样的对象:

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding]  options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil ];



        if ( UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad )
        {
//            overView.font = [UIFont systemFontOfSize:16];
            [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(0, attributedString.length)];
        }
        else{
//            overView.font = [UIFont systemFontOfSize:12];
            [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:NSMakeRange(0, attributedString.length)];
        }
        overView.attributedText = (NSAttributedString *)attributedString;

如何检查此对象以检查其中一个属性是否为null / undefined,并告诉我哪一个?

我可以写一个循环,但如果有更快的方法,它可能会更好。

2 个答案:

答案 0 :(得分:2)

以这种方式检查

var nullProps = Object.keys( $scope.contact ).filter( function( key, index, arr ){ return typeof $scope.contact[ key ] == "undefined";  })

这实质上是迭代对象$scope.contact的所有属性,只返回值为nullundefined的那些属性。

答案 1 :(得分:1)

您可以使用辅助函数来过滤具有空值/未定义值的键:



const obj = {
    name: 'Name',
    id: 1000,
    here: null,
    parent: undefined,
    zero: 0,
    bool: false    
}

const emptyKeys = obj => Object.keys(obj).filter(key => obj[key] == null)

const r = emptyKeys(obj);

console.log(r);




相关问题