简体   繁体   中英

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

Python's get method for dictionaries lets me specify what should be returned if a key doesn't exist. For my current case I want a dictionary returned. How do I do this in Javascript?

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

JavaScript has no helper feature to do that. You need to test explicitly.

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

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

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

You could 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 trough an handler. In this case we can write/access propertys of dictionary normally, but if we access values that do not exist it'll return "Default"

I prefer to use the logical OR like this:

foo.bar || 'default'

If checks is foo.bar is falsy, so it returns 'default' if bar is undefined.

You just need to care, that foo is an object. Otherwise a ReferenceError is thrown.

this works for me

let obj = {"a": 1};
let default = 100
obj["a"] || default; // -> 1
obj["b"] || default; // -> 100

But! there are some limitation, if !!obj["a"] === false we always get default value... so it's better to just check if key in obj, to be completely sure.

With modern javascript you can use the ?? operator

const result = obj[key] ?? default;

Note that cases like {myKey: undefined} or {myKey: null} will also return the default value, which may or may not be the desired behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM