1. ホーム
  2. javascript

[解決済み] 未定義のオブジェクトに自動的にプロパティを追加するには?

2023-02-20 11:08:52

質問

オブジェクトにプロパティが存在しない場合、自動的に追加する簡単な方法はありますか?

次のような例を考えてみましょう。

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

これは hello が定義されていないからです。

なぜこれを尋ねるかというと、いくつかの既存のオブジェクトがありますが、それらがすでに hello を持つかどうかわからないオブジェクトがあるからです。実際、私のコードのさまざまな部分にこれらのオブジェクトがたくさんあります。 常に hello が存在するかどうかを常にチェックし、存在しない場合は新しいオブジェクトを作成するのは非常に面倒です。

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

のようなオブジェクトを自動的に作成する方法はありますか? hello のようなオブジェクトを自動的に作成する方法はありますか?

phpのようなものということです。

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

出力します。

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

OKそれは配列ですが、jsの配列ではオブジェクトと同じ問題です。

どのように解決するのですか?

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

もし test.hello が未定義の場合、空のオブジェクトが設定されます。

もし test.hello が以前に定義されていた場合、それは変更されないままです。

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.