Michael R. Michael R. - 1 month ago 19
JSON Question

Mobx observable deep object

I looking for best solution how to implement @observable on deep json object structure (for example a tree) data tree could be go really deep. and each node has many properties, but I need to observe only one property in tree node. Simply if I do

@observable questionnaire = {}


it works, but i think that is waist. I need observe only 'selected' property.
Here is json structure. Please correct me if i'm wrong here is questionnaire object simplified.

[
{
"id": "1",
"title": "level 1",
"description": "text",
"type": "Question",
"selected": false,
"childNodes": [
{
"title": "level 2",
"description": "text",
"type": "Question",
"selected": false,
"childNodes": [
{
"title": "level 3",
"description": null,
"type": "Question",
"selected": false,
"childNodes": [
{
"title": "level 4 1",
"childNodes": [],
"description": null,
"type": "Checkbox",
"selected": false
},
{
"title": "level 4 2",
"childNodes": [],
"description": null,
"type": "Checkbox",
"selected": false
},
{
"title": "level 4 3",
"childNodes": [],
"description": null,
"type": "Checkbox",
"selected": false
},
...
]
}, ...

Answer

One way is to have a Node class implemented as follows:

class Node {
  @observable selected = false;
  @observable childNodes = [];

  constructor(data) {
    // Recursively create `Node` objects for all children.
    data.childNodes = data.childNodes.map(child => new Node(child));
    Object.assign(this, data);
  }
}

Then you create a Node object from your top-level json object: new Node(json).

This solution will only observe selected and childNodes. It's not ideal because you need to wrap your json object in Node objects. But I can't think of any other way to do it.

Comments