0

我总是需要处理属性存在不确定的多级 js 对象:

try { value1 = obj.a.b.c; } catch(e) { value1 = 1; }
try { value2 = obj.d.e.f; } catch(e) { value2 = 2; }
......

是否有不需要大量尝试捕获的更简单方法或通用函数(例如 ifnull(obj.def, 2) )?

4

3 回答 3

5
var value1 = (obj.a && obj.a.b && obj.a.b.c) || 1;

http://jsfiddle.net/DerekL/UfJEQ/

或者使用这个:

function ifNull(obj, key, defVal){
    var keys = key.split("."), value;
    for(var i = 0; i < keys.length; i++){
        if(typeof obj[keys[i]] !== "undefined"){
            value = obj = obj[keys[i]];
        }else{
            return defVal;
        }
    }
    return value;
}

var value1 = ifNull(obj, "a.b.c", 1);
于 2013-08-19T03:41:30.680 回答
2

你总是可以创建一个辅助函数。

function isUndefined(root, path, defaultVal) {
    var parts = path.split('.'),
        i = 0,
        len = parts.length,
        o = root || {}, v;

    while ((typeof (v = o[parts[i]]) === 'object', o = v) && ++i < len);

    return (typeof v === 'undefined' || i !== len)? defaultVal: v;

}

var obj = {a: { b: { test: 'test' }}}, v;
v = isUndefined(obj, 'a.b.test', 1); //test
v = isUndefined(obj, 'a.test', 1); //1
于 2013-08-19T04:50:23.833 回答
0

使用 lodash 你可以轻松做到这一点**(节点存在并对该节点进行空检查)**..

var lodash = require('lodash-contrib');

function invalidateRequest(obj, param) {
    var valid = true;

    param.forEach(function(val) {
        if(!lodash.hasPath(obj, val)) {
            valid = false;
        } else {
            if(lodash.getPath(obj, val) == null || lodash.getPath(obj, val) == undefined || lodash.getPath(obj, val) == '') {
                valid = false;
            }
        }
    });
    return valid;
}

用法:

leaveDetails = {
              "startDay": 1414998000000,
              "endDay": 1415084400000,
              "test": { "test1" : 1234 }
    };

    var validate;

    validate = invalidateRequest(leaveDetails, ['startDay', 'endDay', 'test.test1']);

它将返回布尔值。

于 2014-11-06T08:21:40.100 回答