Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to automatically add properties to an object that is undefined?

Tags:

javascript

Is there an easy way to automatically add properties to objects if they don't already exist?

Consider the following example:

var test = {}
test.hello.world = "Hello doesn't exist!"

This doesn't work because hello isn't defined.

The reason why I'm asking this is because I have some existing objects for which I don't know if they allready have hello or not. I actually have a lot of these objects in different parts of my code. It is very annoying to always check if hello exists and if it doesn't create a new object like:

var test = {}
if(test.hello === undefined) test.hello = {}
test.hello.world = "Hello World!"

Is there a way to automatically create an object like hello in this example?

I mean something like that in php:

$test = array();  
$test['hello']['world'] = "Hello world";   
var_dump($test);

Output:

array(1) {
  ["hello"] => array(1) {
    ["world"] => string(11) "Hello world"
  }
}

Ok it's an array but in js arrays it is the same problem as with objects.

like image 499
Marcel Gwerder Avatar asked Jul 14 '13 21:07

Marcel Gwerder


People also ask

How do you conditionally add property to an object?

To conditionally add a property to an object, we can make use of the && operator. In the example above, in the first property definition on obj , the first expression ( trueCondition ) is true/truthy, so the second expression is returned, and then spread into the object.

How do you add a dynamic property to an object?

Use an index signature to dynamically add properties to an object, e.g. const obj: {[key: string]: any} = {} .

How do you add properties to an existing object?

To change a value of the existing property of an object, specify the object name followed by a square bracket, the name of the property you wish to change, an equals sign, and the new value you want to assign.

Can we add dynamically named properties to JavaScript object?

So the best way of adding dynamically created property is the [bracket] method. Show activity on this post. Example: ReadValue("object.


2 Answers

var test = {};
test.hello = test.hello || {};
test.hello.world = "Hello world!";

If test.hello is undefined, it gets set to an empty object.

If test.hello was previously defined, it stays unchanged.

var test = {
  hello : {
    foobar : "Hello foobar"
  }
};

test.hello = test.hello || {};
test.hello.world = "Hello World";

console.log(test.hello.foobar); // this is still defined;
console.log(test.hello.world); // as is this.
like image 196
xbonez Avatar answered Oct 11 '22 05:10

xbonez


You can use the Logical nullish assignment (??=):

var test = {};
(test.hello ??= {}).world ??= "Hello doesn't exist!";
like image 58
DexBG Avatar answered Oct 11 '22 04:10

DexBG