Set default attributes of javascript object

Is there a way to set the default attribute for a javascript object so that:

var emptyObj = {}; // do some magic emptyObj.nonExistingAttribute // => defaultValue 

IE can be ignored, Chrome Frame saved me from this headache.

+65
javascript
Jul 06 '11 at 17:59
source share
15 answers

Since I asked a question a few years ago, everything went well.

Proxies are part of ES6. The following example works in Chrome, Firefox, Safari, and Edge :

 var handler = { get: function(target, name) { return target.hasOwnProperty(name) ? target[name] : 42; } }; var p = new Proxy({}, handler); p.answerToTheUltimateQuestionOfLife; //=> 42 



Read more in the Mozilla Proxies Documentation .

+80
Apr 18 '15 at 23:02
source share
β€” -

Unable to set this in Javascript - returning undefined for nonexistent properties is part of the core Javascript specification. See a discussion of this similar question . As I suggested, one approach (although I cannot recommend it) would be to define a global getProperty function:

 function getProperty(o, prop) { if (o[prop] !== undefined) return o[prop]; else return "my default"; } var o = { foo: 1 }; getProperty(o, 'foo'); // 1 getProperty(o, 'bar'); // "my default" 

But this will lead to a bunch of non-standard code that will be difficult for others to read, and this can have unintended consequences in areas where you expect or want an undefined value. Better to just check how you go:

 var someVar = o.someVar || "my default"; 
+27
Jul 06 2018-11-18T00:
source share

Use destructuring (new in ES6)

There is excellent documentation from Mozila , as well as a fantastic blog post that explains the syntax better than me.

Answer your question

 var emptyObj = {}; const { nonExistingAttribute = defaultValue } = emptyObj; console.log(nonExistingAttribute); // defaultValue 

Move on

Can I rename this variable? Sure!

 const { nonExistingAttribute: coolerName = 15} = emptyObj; console.log(coolerName); // 15 

What about nested data? Bring it!

 var nestedData = { name: 'Awesome Programmer', languages: [ { name: 'javascript', proficiency: 4, } ], country: 'Canada', }; var {name: realName, languages: [{name: languageName}]} = nestedData ; console.log(realName); // Awesome Programmer console.log(languageName); // javascript 
+18
Sep 08 '17 at 9:12 on
source share

This is similar to a typical use of protoype-based objects:

 // define a new type of object var foo = function() {}; // define a default attribute and value that all objects of this type will have foo.prototype.attribute1 = "defaultValue1"; // create a new object of my type var emptyObj = new foo(); console.log(emptyObj.attribute1); // outputs defaultValue1 
+10
Jul 06 2018-11-11T00:
source share

my code is:

 function(s){ s = { top: s.top || 100, // default value or s.top left: s.left || 300, // default value or s.left } alert(s.top) } 
+10
03 Feb '14 at 16:37
source share

Or you can try this

 dict = { 'somekey': 'somevalue' }; val = dict['anotherkey'] || 'anotherval'; 
+5
May 10 '12 at 6:54
source share

I achieved this using the object.assign function

 const defaultProperties = { 'foo': 'bar', 'bar': 'foo' }; const overwriteProperties = { 'foo': 'foo' }; const newObj = Object.assign({}, defaultProperties, overwriteProperties); console.log(defaultProperties); // {"foo": "bar", "bar": "foo"} console.log(overwriteProperties); // { "foo": "foo" }; console.log(newObj); // { "foo": "foo", "bar": "foo" } 
+4
Aug 13 '18 at 18:35
source share

I think the easiest approach is using Object.assign .

If you have this class:

 class MyHelper { constructor(options) { this.options = Object.assign({ name: "John", surname: "Doe", birthDate: "1980-08-08" }, options); } } 

You can use it as follows:

 let helper = new MyHelper({ name: "Mark" }); console.log(helper.options.surname); // this will output "Doe" 

Documentation (using polyfill): https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

+3
Jul 05 '17 at 14:16
source share

The simplest of all solutions:

 dict = {'first': 1, 'second': 2, 'third': 3} 

Now

 dict['last'] || 'Excluded' 

will return Excluded, which is the default value.

+3
May 21 '18 at 15:01
source share

Yesterday I saw an article mentioning the Object.__noSuchMethod__ property Object.__noSuchMethod__ : JavascriptTips I had no way to play with it, so I don’t know about browser support, but maybe you could use it in some way?

+2
Jul 06 2018-11-18T00:
source share

I am surprised that no one mentioned the ternary operator.

 var emptyObj = {a:'123', b:'234', c:0}; var defaultValue = 'defaultValue'; var attr = 'someNonExistAttribute'; emptyObj.hasOwnProperty(attr) ? emptyObj[attr] : defaultValue;//=> 'defaultValue' attr = 'c'; // => 'c' emptyObj.hasOwnProperty(attr) ? emptyObj[attr] : defaultValue; // => 0 

Thus, even if the value of "c" is 0, it will still get the correct value.

+2
Feb 27 '15 at 7:35
source share

In fact, it is possible to do this with Object.create . It will not work for "undefined" properties. But for those who have been assigned a default value.

 var defaults = { a: 'test1', b: 'test2' }; 

Then, when you create your properties object, you do this with Object.create

 properties = Object.create(defaults); 

Now you will have two objects where the first object is empty, but the prototype points to the defaults object. To check:

 console.log('Unchanged', properties); properties.a = 'updated'; console.log('Updated', properties); console.log('Defaults', Object.getPrototypeOf(properties)); 
0
May 12 '14 at 18:45
source share

One approach is to take the default object and combine it with the target object. The target will override the values ​​in the default object.

jQuery has a .extend() method that does this. However, jQuery is not needed because there are options for implementing JS Vanilla, which can be found here:

http://gomakethings.com/vanilla-javascript-version-of-jquery-extend/

0
May 27 '16 at 6:24
source share
 Object.withDefault = (defaultValue,o={}) => { return new Proxy(o, { get: (o, k) => (k in o) ? o[k] : defaultValue }); } o = Object.withDefault(42); ox //=> 42 ox = 10 ox //=> 10 o.xx //=> 42 
0
Jan 17 '18 at 14:39
source share

I came here looking for a solution because the title matched my description of the problem, but this is not what I was looking for, but I found a solution to my problem (I wanted to have a default value for an attribute that would be dynamic, like date).

 let Blog = { title : String, image : String, body : String, created: {type: Date, default: Date.now} } 

The code above was the solution for which I finally stopped.

-one
Dec 27 '18 at 0:26
source share



All Articles