バージョン10.5.0の新機能。
Overview
dictionaryデータ型を使用して、 値とペアになった一意の String キーのコレクションを管理できます。dictionary データは Javascript Object 型にマッピングします。
Realm オブジェクトモデル
スキーマで混合値の辞書を定義するには、フィールドのデータ型を空のオブジェクト( "{}" )に設定します。 あるいは、特定の型の値を含む辞書を作成するには、括弧の前にデータ型を追加します。 たとえば、 "int{}"は辞書値が整数である必要があることを指定し、 "string{}"は辞書値が文字列である必要があることを指定します。
const PersonSchema = { name: "Person", properties: { name: "string", home: "{}", }, };
Realm では、マップキーに.または$文字を使用できません。 パーセント エンコーディングとデコーディング を使用して、これらの許可されていない文字の 1 つを含むマップキーを保存できます。
// Percent encode . or $ characters to use them in map keys const mapKey = "kitchen.windows"; const encodedMapKey = mapKey.replace(".", "%2E");
値を持つ辞書オブジェクトの作成
Realm.create() メソッドを実行して、辞書値を持つオブジェクトを作成 書込みトランザクション (write transaction) 内のメソッドです。
let johnDoe; let janeSmith; realm.write(() => { johnDoe = realm.create("Person", { name: "John Doe", home: { windows: 5, doors: 3, color: "red", address: "Summerhill St.", price: 400123, }, }); janeSmith = realm.create("Person", { name: "Jane Smith", home: { address: "100 northroad st.", yearBuilt: 1990, }, }); });
辞書プロパティを持つオブジェクトのクエリ
クエリをフィルタリングするには、コレクション.filtered() を実行し、1 つ以上のオブジェクトプロパティの値に基づいて結果のサブセットを指定します。括弧表記を使用すると、辞書のプロパティの値に基づいて結果を指定できます。
また、 <dictionary>.@keysまたは<dictionary>.@valuesを使用して、結果コレクションに特定のキーや値があるかどうかを判断することもできます。 たとえば、ネストされたhome辞書を含むPersonコレクションがある場合、クエリを実行するとhome.@keys = "price" "price"プロパティを持つhomeを持つすべてのPersonオブジェクトを返すことができます。
// query for all Person objects const persons = realm.objects("Person"); // run the `.filtered()` method on all the returned persons to // find the house with the address "Summerhill St." const summerHillHouse = persons.filtered( `home['address'] = "Summerhill St."` )[0].home; // Find all people that have a house with a listed price const peopleWithHousesWithAListedPrice = persons.filtered( `home.@keys = "price" ` ); // find a house that has any field with a value of 'red' const redHouse = persons.filtered(`home.@values = "red" `)[0].home;
辞書へのリスナーの追加
辞書.addLister()メソッドを実行することで、辞書にリスナーを追加できます 使用して複数のドキュメントを挿入できます。 addListenerメソッドのコールバック関数には、変更された辞書と、辞書が変更された方法を説明する変更の配列の 2 つのパラメータがあります。
summerHillHouse.addListener((changedHouse, changes) => { console.log("A change has occurred to the Summer Hill House object"); });
辞書の更新
辞書のプロパティを更新するには、ドット表記またはdictionary.put()メソッドを使用します。
realm.write(() => { // use the `set()` method to update a field of a dictionary summerHillHouse.set({ price: 400100 }); // alternatively, update a field of a dictionary through dot notation summerHillHouse.color = "brown"; // update a dictionary by adding a field summerHillHouse.yearBuilt = 2004; });
辞書のメンバーの削除
辞書のノードを削除するには、辞書から削除するプロパティの配列を指定したdictionary.remove()メソッドを使用します。
realm.write(() => { // remove the 'windows' and 'doors' field of the Summerhill House. summerHillHouse.remove(["windows", "doors"]); });