Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
121 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...