What is the Javascript equivalent of Python’s get method for dictionaries

There is no javascript equivalent of the python dictionary get method. If you would write it yourself, as a function, it would look 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 a prototype of obj.

If you really want a method rather than a function (obj.get("a", 2)), you need to extend the prototype of Object. This is generally considered a bad idea though, see Extending Object.prototype JavaScript

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)