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.
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.
Use an index signature to dynamically add properties to an object, e.g. const obj: {[key: string]: any} = {} .
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.
So the best way of adding dynamically created property is the [bracket] method. Show activity on this post. Example: ReadValue("object.
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.
You can use the Logical nullish assignment (??=):
var test = {};
(test.hello ??= {}).world ??= "Hello doesn't exist!";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With