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
},
...
]
}, ...
One way is to have a Node
class implemented as follows:
class Node {
@observable selected = false;
@observable childNodes = asFlat([]);
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.