JavaScript,检查嵌套对象属性是否为空/未定义的优雅方式 [英] JavaScript, elegant way to check nested object properties for null/undefined

查看:38
本文介绍了JavaScript,检查嵌套对象属性是否为空/未定义的优雅方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我时不时遇到的一个问题"是我有一个对象,例如user = {} 并在使用应用程序的过程中填充.让我们说某处,在 AJAX 调用或我这样做之后:

a "problem" which i have every now and then is that i have an object e.g. user = {} and through the course of using the app this gets populated. Let's say somwhere, after an AJAX call or something i do this:

user.loc = {
    lat: 50,
    long: 9
}

在另一个地方我想检查 user.loc.lat 是否存在.

At another place i want to check if user.loc.lat exists.

if (user.loc.lat) {
    // do something
}

如果它不存在,这将导致错误.如果user.loc.latundefineduser.loc当然也是undefined.

If it does not exists, this will cause an error. If user.loc.lat is undefined, user.loc of course is undefined as well.

"Cannot read property 'lat' of null" - Dev Tools error

这意味着我需要像这样检查它:

That means I need to check it like this:

if (user.loc) {
    if (user.loc.lat) {
        // do something
    }
}

if (user.loc && user.loc.lat) {
    // do something
}

这不是很漂亮,我的对象越大越糟糕 - 显然(想象 10 级嵌套).如果 user.locundefined<,if(user.loc.lat) 不只是返回 false/code> 也是.

This isn't really pretty and the bigger my objects are the worse it gets - obviously (imagine 10 levels of nesting). It kind bums me that if(user.loc.lat) isn't just returning false if user.loc is undefined as well.

检查此类情况的理想方法是什么?

What's the ideal way to check situations like this?

推荐答案

您可以使用这样的实用函数:

You can use an utility function like this:

get = function(obj, key) {
    return key.split(".").reduce(function(o, x) {
        return (typeof o == "undefined" || o === null) ? o : o[x];
    }, obj);
}

用法:

 get(user, 'loc.lat')     // 50
 get(user, 'loc.foo.bar') // undefined

或者,仅检查属性是否存在,而不获取其值:

Or, to check only if a property exists, without getting its value:

has = function(obj, key) {
    return key.split(".").every(function(x) {
        if(typeof obj != "object" || obj === null || ! x in obj)
            return false;
        obj = obj[x];
        return true;
    });
}

if(has(user, 'loc.lat')) ...

这篇关于JavaScript,检查嵌套对象属性是否为空/未定义的优雅方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆