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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…