immutable.js - updating specific nodes within intricate and deeply nested objects

I am looking to replace a fragment of my JSON object with another part using immutable.js.

Consider the example below where we have a more complex and nested object. I want to update/replace the node with "id": "F" with a different edited node.

As per the documentation, I need to extract the `keyPath` as an array and pass it to the function

setIn(keyPath: Array<any>, value: any): Map<K, V>
.

Therefore, I need to find the keypath for F: [ 'children', 2, 'children', 0, 'children', 0 ] (is this correct?).

This is just a simplified example. In my scenario, the keypath has a much more elaborate hierarchy. How can I achieve this using immutable.js or plain JS? Is this approach accurate? Are there more elegant solutions to achieve the same behavior (preferably utilizing immutable.js functions)?

Best regards,

Rafal

Example:

{ 
    "id": "A",
    "children": [
        {
            "id": "B",
            "children": [

            ]
        },
        {
            "id": "C",
            "children": [

            ]
        },
        {
            "id": "D",
            "children": [
                {
                    "id": "E",
                    "children": [
                        {
                            "id": "F", // THIS NODE WILL BE UPDATED
                            "children": [

                            ]
                        }
                    ]
                },
                {
                    "id": "G",
                    "children": [

                    ]
                }
            ]
        }
    ]
}

Answer №1

If you have a efficient method for determining the keyPath of the specific node you want to update, then using .setIn() can be a simple and effective solution.

Of course, there are alternate approaches depending on the nature of the problem you're addressing.

In the scenario provided, if the id property is indeed unique and you have information about what you're searching for (such as "id": "F" somewhere in the tree), utilizing .updateIn() with predicate functions can help locate and modify the desired node. Consider implementing DFS or BFS based on your requirements. For List structures, .find() and .findIndex() may also prove useful in certain compositions.

Another aspect to consider is data flattening. While not always a popular choice, it can simplify tasks and improve usability for various UI components.

In the case of your graph example, flatten it into a List of Maps where each item holds references to their children and/or parents' uuids. This way, traversing the List allows for easy identification and updating of elements based on straightforward predicates.

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

What seems to be the issue with the useState hook in my React application - is it not functioning as

Currently, I am engrossed in a project where I am crafting a Select component using a newfound design pattern. The execution looks flawless, but there seems to be an issue as the useState function doesn't seem to be functioning properly. As a newcomer ...

Issue encountered when utilizing FontAwesome in xhtml file in jdeveloper

Attempting to integrate font-awesome into my .xhtml page is proving to be a challenge, resulting in errors as shown in the image below. My development environment is Jdeveloper 12.2.1. Despite researching various topics, I have yet to find a solution. An ...

Looking for a specific value prior to the '.' character in BASH

I need some help with outputting values in JSON format. I noticed that if a value starts with a '.', it causes issues because the API doesn't like integers inside quotation marks. Can someone suggest the best approach to check if a value has ...

Error: Docker-compose is unable to locate the specified module

Struggling to convert my docker-compose.yml file from using mongodb to mysql. Each time I add a new dependency, it shows it cannot be found... Cannot find module 'sequelize' Even after running docker-compose build, the issue persists. I suspect ...

Making an Axios request with parameters

I am facing an issue where my parameter articleid is not being passed to the route /createAnswer. When I log articleData._id, it shows the correct ID (e.g., 60b4f5d8c8be1d4cb0cdd6ca) that I want to pass to the route /createAnswer. const createAnswer = () = ...

Vue's v-bind:style does not support background image-set() functionality

Currently, I am utilizing Vue's v-bind:style feature to set the background of a div, which is functioning properly. However, I am facing an issue when attempting to use background in combination with image-set(). When using a regular background-image, ...

The $digest function in Angular's $rootScope

While engrossed in the incredible book, Mastering Web Development in AngularJS, I stumbled upon this code snippet: var Restaurant = function ($q, $rootScope) { var currentOrder; this.takeOrder = function (orderedItems) { currentOrder = { deferred ...

Maintaining the gridview header position during scrolling

When I fixed the header of my GridView and scrolled down, the headers remained constant but were not displayed properly. All the column headers appeared shrinked and did not align with the respective columns. Despite trying various solutions, nothing seeme ...

Dropdown menu will appear when you click on one of the menu items

Can someone help me create a dropdown menu using a JavaScript function that toggles on click? I've attempted to do so with the following code, but it's not working as expected. Could you please point out where I might be going wrong? I'm loo ...

CSS footer element refuses to disappear

This sample application features a header, footer, and a content div that includes a table displaying various statistics of basketball players. One issue I encountered was with the footer when there were many entries in the table. This caused the footer t ...

Executing a jQuery AJAX request for a second time

Upon hitting the submit button for the first time, the codes work successfully. However, upon hitting the button for the second time with correct email and password values, nothing happens and the user cannot log in. I have identified that the issue lies w ...

Change events are not being received upon clicking the radio buttons

Hey friends, I'm trying to set up backbone events for when radio buttons are clicked. Here are the radio buttons I have: <p><label for="pays">Pays now</label><input id="pays" name="pays" type="radio" value="1" class="_100"/>&l ...

Executing JavaScript code does not execute CSS code

Having some trouble with my Javascript and CSS. The script is functioning well, but when I use the filtering function, the CSS stops working and only the filtered results are displayed on the HTML page. Looking for advice on how to fix the Javascript. & ...

Passing a single item from a list as a prop in Vue.js

Imagine having the following set of information in data: data: { todos: [ { id: 1, title: "Learn Python" }, { id: 2, title: "Learn JS" }, { id: 3, title: "Create WebApp" } ] } Now, I aim to send only the item with an id of 2 t ...

`Need help with navigating through nested JSON API data in SwiftUI?`

I'm currently working on creating a public transport app using SwiftUI. I have access to an API that allows me to search for origin and destination stations in Stockholm, Sweden, along with the desired date and time of travel to retrieve a travel rout ...

Error message stating that VueRouter is not defined during karma unit tests

I'm encountering warnings during the tests on my new Vue.js project. Whenever a component utilizes the router, either in the template as a <router-link> or programmatically as this.$router.push('/'); The tests are passing but these wa ...

Troubleshooting Firefox's inability to properly utilize jQuery's scrollTop() function on the 'body' element

I'm puzzled as to why the scrollTop() jquery function isn't functioning properly on the 'body' element in Firefox. $('body').scrollTop(0); To resolve this issue, I ended up using: $(window).scrollTop(0); The jquery documen ...

Tips for making Slider display the next or previous slide when span is clicked

I have implemented a mix of bootstrap 3 and manual coding for my project. While the image thumbnails function correctly when clicked, the span arrows do not navigate to the next or previous images as intended. Below is the code snippet: var maximages ...

Managing JSON data through AJAX in ColdFusion

For my external API call using AJAX, I am incorporating a local API setup as an intermediate step. The process is as follows: The Ajax call sends data to localAPI.cfm. Within localAPI.cfm, there is a <cfhttp> tag to forward the data to an external ...

While iterating over the key with a variable in a loop, only one property is displayed consistently instead of four different

Currently, I am working on creating an address book using JavaScript. The problem I am facing is that the properties of my objects are not providing me with the necessary information. I need 4 different properties instead of 4 loops with the same property. ...