相当于python的dictionary.get的javascript

Kev*_*son 5 javascript node.js underscore.js

我正在尝试使用node.js验证JSON对象。基本上,如果条件A存在,那么我要确保数组中可能不存在特定值。我使用dictionary.get在python中执行此操作,因为如果我查找不存在的内容,它将返回默认值。这就是python中的样子

if output.get('conditionA') and not 'conditionB' in output.get('deeply', {}).get('nested', {}).get('array', []):
    print "There is an error somewhere you need to be fixing."
Run Code Online (Sandbox Code Playgroud)

我想为JavaScript找到类似的技术。我尝试在下划线中使用默认值来创建密钥(如果它们不存在的话),但我认为我做的不正确,或者我没有按预期的方式使用它。

var temp = _.defaults(output, {'deeply': {'nested': {'array': []}}});
if (temp.hasOwnProperty('conditionA') && temp.deeply.nested.array.indexOf('conditionB') == -1) {
    console.log("There is an error somewhere you need to be fixing.");
}
Run Code Online (Sandbox Code Playgroud)

看起来,如果它遇到缺少嵌套对象之一的输出,则不会用默认值替换它,而是用TypeError: Cannot read property 'variety' of undefined“ variety”作为我正在查看的数组的名称来打击。

Cli*_*ell 4

或者更好的是,这里有一个模仿 python 字典功能的快速包装器。

http://jsfiddle.net/xg6xb87m/4/

function pydict (item) {
    if(!(this instanceof pydict)) {
       return new pydict(item);
    }
    var self = this;
    self._item = item;
    self.get = function(name, def) {
        var val = self._item[name];
        return new pydict(val === undefined || val === null ? def : val);
    };
    self.value = function() {
       return self._item;
    };
    return self;
};
// now use it by wrapping your js object
var output = {deeply: { nested: { array: [] } } };
var array = pydict(output).get('deeply', {}).get('nested', {}).get('array', []).value();
Run Code Online (Sandbox Code Playgroud)

编辑

另外,这是一种快速但肮脏的方法来执行嵌套/多个条件:

var output = {deeply: {nested: {array: ['conditionB']}}};
var val = output["deeply"]
if(val && (val = val["nested"]) && (val = val["array"]) && (val.indexOf("conditionB") >= 0)) {
...
}
Run Code Online (Sandbox Code Playgroud)

编辑 2根据 Bergi 的观察更新了代码。