Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 334
Tim Clemans Avatar asked May 25 '17 15:05

Tim Clemans


People also ask

What is the equivalent of a Python dictionary in JavaScript?

Python and javascript both have different representations for a dictionary. So you need an intermediate representation in order to pass data between them. The most commonly used intermediate representation is JSON, which is a simple lightweight data-interchange format. The dumps function converts the dict to a string.

Is there a dictionary in JavaScript?

Are there dictionaries in JavaScript? 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.

What is get method in dictionary Python?

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

What are dictionaries in JavaScript called?

The data stored in the form of key-value pairs is called an Object or a Dictionary. Objects and dictionaries are similar; the difference lies in semantics. In JavaScript, dictionaries are called objects, whereas, in languages like Python or C#, they are called dictionaries.


1 Answers

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

like image 84
pj.dewitte Avatar answered Sep 30 '22 19:09

pj.dewitte