Encompassing object with Mobx observables

I am searching for the best approach to implement @observable on a deeply nested JSON object structure, such as a tree. The data tree can go quite deep, with each node having multiple properties. However, I only need to observe one specific property in each tree node. When I use

@observable questionnaire = {}

it works, but I believe this is inefficient. I want to observe only the 'selected' property. Here is an example of the JSON structure. Please correct me if I am mistaken. Here is a simplified version of the questionnaire object:

[
  {
    "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 №1

To implement a structure where each node can be observed for changes, you can define a Node class like so:

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

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

You can then instantiate a Node object using your top-level JSON object: new Node(json).

This method allows observation of changes in the selected and childNodes properties. Although it requires wrapping the original JSON in Node objects, this approach enables effective monitoring of changes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

PHP - Extract Information from Table Upon Form Submission without User Input

I'm facing a challenge with my web form that includes a table allowing users to delete rows before submitting. Although there are no input fields in the table, I need to capture the data from these rows when the form is submitted. The issue is that th ...

Having trouble with loading JavaScript during ng build --prod process

The JavaScript file I'm using for multiple emails (multiple_emails.js plugin) works well with ng serve. Here is my code: (function( $ ){ $.fn.multiple_emails = function(options) { // Default options var defaults = { ...

Save room for text that shows up on its own

I am currently dealing with a situation where text appears conditionally and when it does, it causes the rest of the page to be pushed down. Does anyone know the best way to reserve the space for this text even when it's not visible so that I can pre ...

jQuery UI Dialog is causing my DOM elements to shift positions

I encountered an issue where my jquery ui dialog would only open once, To address this, I attempted the following solution: /* Prepare */ $('.steps > div.step-1 .bicicleta .attributos').dialog({ autoOpen:false, width: ...

Display a form with hidden input that dynamically updates on any input change

<form id="pricecal"> <input type="text" onchange="calprice()" class="form-control round-corner-fix datepicker" data-provide="datepicker" placeholder="Check in" value="" required /> <input type="text" onchange="calprice()" class="form ...

Verify login availability using Javascript auto-check

For quite some time now, I've been grappling with a significant issue that has been consuming my attention. I am determined to implement an auto-check login availability feature in the registration form of my website. My goal is for it to verify the ...

Creating a conditional statement within an array.map loop in Next.js

User Interface after Processing After retrieving this dataset const array = [1,2,3,4,5,6,7,8] I need to determine if the index of the array is a multiple of 5. If the loop is on index 0, 5, 10 and so on, it should display this HTML <div class="s ...

A guide to sorting an array based on user input using Javascript

I have developed an app that utilizes JavaScript and the VueJS framework. I am currently working on implementing a 'dropdown' feature for items that are dynamically filtered based on user input. Below is the code snippet responsible for renderin ...

Fetching Json data from PHP server

Here is the Json data provided:- {"data":[{"text1":"value1","text2":"value2","text3":"values3"},{"text1":"value1","text2":"value2","text3":"values"},{"text1":"value1","text2":"value2","text3":"values"},{"text1":"value1","text2":"value2","text3":"values"}, ...

Steer clear of duplicating patterns in vue templates

I have a significant issue with a component that needs to be repeated multiple times in the parent template due to the usage of v-if. The component code is as follows: <SelectCard v-for="(channel, index) in category.visibleChannels" :key="index + & ...

Ways to create a looping mechanism with specified number restrictions and limitations

Can anyone assist me with this problem? I am looking to create a "looping" effect similar to the image provided. What is the logic behind this repetition? Thank you in advance for your help! Here is an example output: ...

What are the methods used by Typescript 2 to ensure non-nullable types?

While it is commonly understood that the compiler performs static type checking, I am curious about the specific methods it employs to ensure that nullable types are not inadvertently used. ...

Guide to formatting the timestamp in outgoing JSON

Lately, I've been immersed in exploring Go and it truly is remarkable. One thing that has me scratching my head (even after scouring through documentation and blogs) is how to customize the formatting of the time.Time type when it's encoded using ...

Updating a global variable in Angular after making an HTTP call

I'm facing a challenge where I have a global variable that needs to be updated after an HTTP GET call. Once updated, I then need to pass this updated variable to another function. I'm struggling to figure out the best approach for achieving this. ...

How can I expand all primary accordions while keeping secondary accordions collapsed?

I have a main accordion with nested accordions within each item. My goal is to only expand the main level accordions when clicking the button, without opening the nested ones. I want to open all "Groups" accordions while keeping the sub-accordions labeled ...

Align the center of table headers in JavaScript

I'm currently in the process of creating a table with the following code snippet: const table = document.createElement('table'); table.style.textAlign = 'center'; table.setAttribute('border', '2'); const thead ...

Solving template strings in a future context

I have a unique use-case scenario where I am filling the innerHTML like this. However, my issue lies in resolving the template literal within the context of a for loop. Any suggestions on how to accomplish this? var blog_entries_dom = 'blog_entries& ...

React: Premature exit, Fewer hooks executed than anticipated

I'm currently working on a chrome extension project where I'm trying to update an object based on a change in the current tab. However, I keep encountering an error that says I've rendered fewer hooks than expected. How can I resolve this is ...

Sending POST Requests with Next.js Version 14

How can I send a POST request using axios in Next.js 14, I prefer axios but fetch is also okay. I have been getting an AxiosError: Network Error when I try to use axios and TypeError: fetch failed when using fetch. However, it works fine with Postman. I ...

Calculating Time Difference in JavaScript Without Utilizing moment.js Library

I have two timestamps that I need to calculate the difference for. var startTimestamp = 1488021704531; var endTimestamp = 1488022516572; I am looking to find the time difference between these two timestamps in hours and minutes using JavaScript, without ...