What is the Javascript equivalent of the Python method for dictionaries

Python get method for dictionaries allows me to specify what should be returned if a key does not exist. For my current case, I want a dictionary to return. How do I do this in Javascript?

+3


source to share


3 answers


JavaScript has no helper function for this. You need to test explicitly.

if ("myProperty" in myObject) {
    return { another: "object" };
} else {
    return myObject.myProperty;
}

      



You can use the ternary operator to do the same with less code.

return ("myProperty" in myObject) ? myObject.myProperty : { another: "object" };

      

+2


source


There is no javascript equivalent to the python get-dictionary method. If you write this yourself as a function, it looks like this:

function get(object, key, default_value) {
    var result = object[key];
    return (typeof result !== "undefined") ? result : default_value;
}

      

Use it like:



var obj = {"a": 1};
get(obj, "a", 2); // -> 1
get(obj, "b", 2); // -> 2

      

Note that the requested key will also be found in the obj prototype.

If you really want a method and not a function ( obj.get("a", 2)

), you need to extend the object prototype. This is generally considered a bad idea, see Extending JavaScript to Object.prototype

+2


source


You can use a proxy for this (really new):

var handler = {
    get: function(target, name){
        return name in target?
        target[name] :
        "Default";
    }
};
var dictionary={"hi":true};
var dict = new Proxy(dictionary, handler);
dict.a = 1;
dict.b = undefined;

console.log(dict.a, dict.b,dict.hi); // 1, undefined,true
console.log(dict.new); //"Default"

 //the proxied object gets changed:

console.log(dictionary.a, dictionary.b,dictionary.hi); // 1, undefined,true
console.log(dictionary.new); //undefined

      

A proxy is an object that reflects all changes and requests through the handler. In this case, we can write / access the properties of the dictionary normally, but if we access values ​​that do not exist, it will return "Default"

+1


source







All Articles