What is the Javascript equivalent of the Python method for dictionaries
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" };
source to share
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
source to share
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"
source to share