Changing the value in a multi-dimensional array using a specific path represented in array or any other format

In my project, I am dealing with a multidimensional array that represents a deep category tree menu. The structure of the array looks like this:

this.tree = [{
    "title": "1. dragon-breath",
    "items": []
}, {
    "title": "2. moiré-vision",
    "items": [{
        "title": "2.1. tofu-animation",
        "items": [{
            "title": "2.1.1. spooky-giraffe",
            "items": []
            }, {
                "title": "2.1.2. bubble-burst",
                "items": []
            }],
    }, {
        "title": "2.2. barehand-atomsplitting",
        "items": []
    }],
}, {
    "title": "3. unicorn-zapper",
    "items": []
}, {
    "title": "4. romantic-transclusion",
    "items": []
}];

Alongside this array, I have another array called path which points to a specific leaf on the tree. This path can change dynamically over time. For example, it may look like this:

var path = [0]

or like this:

var path = [1][1]

or maybe even like this:

var path = [1][0][1]

Now, the challenge is to update the title attribute of the leaf specified by this path. I have attempted using the eval function as follows:

eval('tree'+getStringPathByArrayPath([1,0,1])+'.name = "'+updatedName+'"')

However, I am aware that using eval is not considered best practice and could be problematic if used repeatedly. Also, since I am using this function in an angular ng-model context, I want to avoid unnecessary evaluations by the browser.

Is there a better approach to solve this issue? Or am I approaching it incorrectly?

PS: I have tried iterating over the path array recursively to access the correct tree node, but encountered issues with referencing and making changes to the original node without creating copies.

Thank you for your assistance.

Answer №1

While Javascript may be considered pass-by-value, it is important to note that when dealing with objects, the variable actually holds a reference to the object itself. Passing this variable will not create a copy of the object, but rather pass the reference to it. As a result, any modifications made to the object through this reference will directly affect the original object. This can be seen in the following code snippet:

let currentNode = this.tree[path[0]];
for (let i = 1; i < path.length; i++) {
  currentNode = currentNode.items[path[i]];
}
currentNode.title = updatedName;

Answer №2

Imagine you have an Array that specifies the steps required to access a specific value;

var path = [1, 0, 1];
//          x  y  z

You also possess a corresponding object

var obj = [
// y     0           1        // x
// z   0    1      0    1     //
    [['a', 'b'], ['c', 'd']], // 0
    [['e', 'f'], ['g', 'h']]  // 1
];

A function can be created to navigate to the desired value like this

function followPath(root, path) {
    var i;
    for (i = 0; i < path.length; ++i)
        root = root[path[i]];
    return root;
}

Using this function in the given example would result in

followPath(obj, path); // "f"

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

Implementing Gatsby-js for client-side JavaScript directly within a blog post is a powerful

I've been working on setting up a blog using Gatsby-JS and have run into a bit of an issue. My posts, written in markdown, include inline javascript like this: <script>window.alert("hello");</script> When I test the site with "Gatsby ser ...

How can I access a property of the model controller when I need to use the ngModel controller?

Implementing ng-repeat and defining a model with it resembles the code snippet below: <div ng-repeat="thing in things" ng-model="thing" my-directive> {{thing.name}} </div> Subsequently, within my directive, the structure typically appear ...

When using jQuery with a large selectbox, you may encounter the error message: "Uncaught RangeError: Maximum

My select box works fine in IE and Mozilla, but throws an uncaught rangeError in Chrome when choosing the "Others" option to display a second select box with over 10k options. How can I diagnose and resolve this issue? <!DOCTYPE html> ...

What is preventing me from accessing these attributes using "${array[a].name}"?

What is preventing me from reading the properties using ${ array[a].name } with For Of loop? I created an example with an array of objects to help diagnose the problem. const movies = [{ title: "Shrek", year: 2001 }, { title: "Shrek 2", ...

Implementing an active class in Vue.js for the router-link component

I am facing an issue with my sidebar item becoming inactive when I click on a sublink inside a component. How can I prevent the active class from switching off? Here is my sidebar: <router-link to='/sub/success_tools_subscriptions' ...

Improve the translation animation on an element containing numerous child nodes

Looking for ways to enhance the smoothness of the transition in the "infinity list" animation. While it's just a demo at the moment, the real app will have various elements emerging from each "pin". The main performance bottleneck seems to stem from t ...

Obtaining a string from a regular expression does not function as anticipated

Currently, I am in the midst of a project that requires me to identify specific HTML tags and replace them with others. To accomplish this task, I am utilizing JavaScript, and the code snippet looks like this: // html to update html = '<div cla ...

The method WebKitBrowser.StringByEvaluatingJavaScriptFromString does not provide any output

After running all JavaScript, I need to retrieve the HTML content. However, I am facing an issue using WebKit.NET where the method WebKitBrowser.StringByEvaluatingJavaScriptFromString does not return anything, even with a simple alert(). When I try passi ...

What is the process for implementing a security rule for sub-maps with unique identifiers in Firebase?

I am looking to implement a security rule ensuring that the quantity of a product cannot go below zero. Client-side request: FirebaseFirestore.instance .collection('$collectionPath') .doc('$uid') .update({'car ...

Determine the difference in time

There are two input types for time: 1. Time of entry. 2. Time of exit. For example: Start: 00:00 End: 01:30 Result: 1.5 Start: 14:00 End: 00:00 Result: 10 An algorithm needs to be created to calculate the number of employees working at a given time. Th ...

What is the best way to extract text from a dynamically changing element using jQuery?

I've been struggling with a coding issue. Despite trying numerous approaches, I keep encountering the same problem where every new button I add ends up having the same text or, alternatively, nothing seems to work as expected. $j serves as my variabl ...

Tips for setting a new key and value for an existing object in TypeScript

As I transition from JavaScript to TypeScript, I am currently working on creating a Discord bot using TypeScript to familiarize myself with the environment. However, I encountered an error when attempting to add new keys to an object that was previously cr ...

Executing a cloud function in Firebase from an Angular-Ionic application by making an HTTP request

I am a newcomer to GCP and app development, so please bear with me if this question seems mundane. Currently, I have an angular-ionic app that is connected to Firebase allowing me to interact with the Firestore database. Now, my challenge is to invoke a ht ...

Dealing with an Angular problem related to parsing JSON data with specific formatting

Currently, I am attempting to use ng-repeat over 'cols' as a starting point. Unfortunately, I am encountering an error when trying to parse this JSON data. { "cols":["id","name","type"], "rows":[ ["284","JAMES DEAN","Employee"], ["243"," ...

Angular 2 - Error: Regular expression missing forward slash syntax

Recently, I began working on an Angular 2 tutorial app using this repository. While I can successfully launch the app and display static content, I am facing challenges with rendering dynamic content from the component. I have a feeling that the error migh ...

Send click events between two canvases

Utilizing a Threejs canvas to showcase a 3D model alongside a hidden Fabricjs canvas for texture application. I successfully converted the 3D coordinates from the Threejs canvas to the 2D canvas. Now, my goal is to transfer the click and drag events from ...

Perform ng-repeat on an array containing several other arrays

This is an angularjs function that retrieves specific categories. $scope.getSpecificCat = function(p_cat) { $http.get(url+'getSpecificCatJson/' + p_cat).success(function(data){ $scope.specifics = data; }).error(functi ...

Utilizing React and Material-UI to create an autocomplete feature for words within sentences that are not the first word

Looking to enable hashtag autocomplete on my webapp, where typing #h would display a menu with options like #hello, #hope, etc. Since I'm using material-ui extensively within the app, it would be convenient to utilize the autocomplete component for th ...

Which is the PREFERRED choice for managing multiple form inputs in React: useState or useRef?

DISCLAIMER: As a newcomer to React, I am striving to establish good programming practices. Imagine a straightforward contacts app scenario, where you input names and they appear below the input field. View pic.1 for a visual of the simple contacts app mec ...

Unable to retrieve JSON data from API through callback

I have developed my own API using PHP. The system includes a dropdown menu that triggers the API call based on the entered keyword. For instance, if the user types in "test," an AJAX call is made to api/search/ with a GET request containing the keyword par ...