Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript equivalent to python's dictionary.get

I'm trying to validate a JSON object with node.js. Basically, if condition A is present then I want to make sure that a particular value is in an array which may not be present. I do this in python using dictionary.get because that will return a default value if I look up something that isn't present. This is what it looks like in 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."

I'd like to find a similar technique for javascript. I tried using defaults in underscore to create the keys if they aren't there but I don't think I did it right or I'm not using it the way it was intended.

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.");
}

It seems like if it runs into an output where one of the nested objects is missing it doesn't replace it with a default value and instead blows with a TypeError: Cannot read property 'variety' of undefined where 'variety' is the name of the array I'm looking at.

like image 580
Kevin Thompson Avatar asked Nov 18 '14 21:11

Kevin Thompson


People also ask

What is the JavaScript equivalent to a dictionary?

While JavaScript doesn't natively include a type called “Dictionary”, it does contain a very flexible type called “Object”. The JavaScript “Object” type is very versatile since JavaScript is a dynamically typed language.

Does JavaScript have dictionaries like Python?

No, as of now JavaScript does not include a native “Dictionary” data type. However, Objects in JavaScript are quite flexible and can be used to create key-value pairs. These objects are quite similar to dictionaries and work alike.

Is there dictionary in JavaScript?

Actually there is no 'dictionary' type in JavaScript but we can create key-value pairs by using JavaScript Objects. Create a new JavaScript Object which will act as dictionary. Syntax: Key can be a string , integer.

What is the dictionary get () method?

Python Dictionary get() Method The get() method returns the value of the item with the specified key.


1 Answers

Or better yet, here's a quick wrapper that imitates the functionality of the python dictionary.

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();

Edit

Also, here's a quick and dirty way to do the nested / multiple conditionals:

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

Edit 2 updated the code based on Bergi's observations.

like image 116
Clint Powell Avatar answered Oct 09 '22 17:10

Clint Powell