Set a Value to a Specific Node in a Multidimensional Array Using JavaScript

Trying to update an element within a JSON object with a new value (text/object/array). I have a swap function that takes in the JSON object, an array with indexes to retrieve the element, and the value to replace it with. Currently using eval, which some consider "evil." Is there a better way to achieve this without eval or is eval acceptable in this scenario? It must be dynamic as the array may change. Also, important to note that the array parameter is programmatically created.

// Example array: ["cluster", "2", "segment", "0", "node", "3"]    
JsonManager.prototype.swap = function(json, array, val){
        var statement = "json";
        for (var i = 0; i < array.length; i++) {
            if(!isNumeric(array[i]))
            {
            statement += "[\"" + array[i] + "\"]";          
            } else {
                statement += "[" + array[i] + "]"   
            }
        }
        statement += " = val";
        eval(statement);
    };

Example JSON Object:

var customers = {
    "cluster": [{
        "clusterid": "cluster1.1",
        "color": "blue",
        // More JSON data here...
    }]
};

Test method:

JsonManager.prototype.init = function(){
    var clause = new Clause("nodeid", "node4.4");
    var indexes = this.search(customers, clause);
    this.swap(customers, indexes.reverse(), {"name": "kevin"});
    var test = customers["cluster"][2]["segment"][0]["node"][3];  
    var breakPoint = "breakpoint";  
};

Solution further commented:

JsonManager.prototype.swap = function(obj, path, value) {

   // Recursively traverse the object 
   function descend(obj, path) {
        
        if (path.length == 0) {
            return obj;
        }
        
       return descend(obj[path[0]], path.slice(1));
    }
    
    var node = descend(obj, path.slice(0, -1));

    node[path[path.length - 1]] = value;
};

Answer №1

Your JSON data is essentially a JavaScript object that forms a tree structure, making it best to navigate using recursive functions.

JsonManager.prototype.swap = function(obj, path, value) {
    function traverse(obj, path) {
        if (path.length == 0) {
            return obj;
        }
        return traverse(obj[path[0]], path.slice(1));
    }

    var node = traverse(obj, path.slice(0, -1));
    node[path[path.length - 1]] = value;
};

Slice extracts portions from an array. Therefore, path.slice(1) removes the first element of the path, while path.slice(0, -1) excludes the last one. This approach allows us to navigate to the second-to-last node in the object and update the final node using standard array notation. To understand this better, visualize the process on paper with a specific example from your data.

Answer №2

A better approach than using eval is to simply assign the object to a variable and then navigate through each level by using that variable:

JsonModifier.prototype.update = function(json, path, value){
  var obj = json;
  for (var i = 0; i < path.length - 1; i++) {
    obj = obj[path[i]];
  }
  obj[path[path.length - 1]] = value;
};

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 are the similarities between using the map function in AngularJS and the $map function in jQuery?

I am currently in the process of migrating jQuery code to AngularJS. I have encountered some instances where the map function is used in jQuery, and I need to replicate the same functionality in AngularJS. Below is the code snippet that demonstrates this. ...

Issue with Ember Select not updating selection binding when populated by another Ember Select

New to Ember.js and grappling with the binding of selection in Select views to the controller. The template I am working with is as follows: {{view Ember.Select contentBinding="content" selectionBinding="selectedCompany" optionLabelPath="content.nam ...

Using private members to create getter and setter in TypeScript

Recently, I developed a unique auto getter and setter in JavaScript which you can view here. However, I am currently unsure of how to implement this functionality in TypeScript. I am interested in creating an Object Oriented version of this feature if it ...

Enhance your React Native app: Utilizing dynamic string variables with react-native-google-places-autocomplete query

I have encountered an issue while attempting to pass a dynamic country code to restrict search results. Here is the code in question: let loc = 'de' <GooglePlacesAutocomplete placeholder="Search" autoFocus={true} onPress ...

The NSException thrown by the TableView

Just diving into Swift and trying to parse JSON using ObjectMapper for displaying data in a TableView, but encountering an issue: libc++abi.dylib: terminating with uncaught exception of type NSException The error occurs after the method numberOfRowsInS ...

Storing the radio button's selected value in local storage using Vue JS

I have a pair of radio buttons that are linked together to accept a boolean value, either true or false. I am trying to implement a functionality where the selected value is stored in local storage. For example, if true is chosen, then true will be saved i ...

The Node.js controller is in disarray

As a newcomer to javascript, node.js, and backend development in general, I am tackling the task of creating a controller for handling login page requests. My confusion lies in extracting data from a MYSQL table, user authentication, and working with the J ...

Creating an array from objects without manual effort

Greetings everyone, currently I am structuring my array in the following manner: var piece1 = new DialoguePiece(null, questions[0], 0, 0, 4, 1); var piece2 = new DialoguePiece(null, questions[1], 1, 0, 2, 3); var piece3 = new DialoguePiece(scripts[1], nul ...

Converting a JSON_ARRAY of IDs to a JSON_ARRAY of values in MySQL 8

I am dealing with a JSON_ARRAY containing ids in the format [1,3,...]. Each id corresponds to a value in another table. Table: animals id | value 1 | lion 2 | monkey 3 | snake Table: animal_owner id | animals_array 1 | [1, 3] 2 | [2] 3 | [] My goal ...

What is the best way to add up values from several different columns

My query is trying to sum multiple columns in a table, but the result is not as expected. Here is the SQL code I am using: SELECT borrower, SUM(collateral_amount) AS collateral_amount, SUM(withdraw_amount) AS withdraw_amount, SUM(total_amount_to_treasure) ...

NSJSONSerialization encounters an error when trying to retrieve data from a particular website

I am encountering some issues while attempting to extract data from a specific URL. Why does my code crash on the line containing NSJSONSerialization? Is there a more efficient method for retrieving information from this website? UPDATE: I modified jsonAr ...

I am interested in generating a Stacked Chart in Google Charts using data from a JSON file

Hey there, I'm looking to generate a stacked chart using JSON data in Google Charts. My current challenge revolves around the code snippet var data = google.visualization.arrayToDataTable([. <?php $tmp = array(); require "configdashboard.php"; /* ...

AngularJS input range is written inside the bubble that crosses over the screen

Is there a way to write inside the bubble of the range slider? I have adjusted the design of the range slider and now I simply want to display the number inside the bubble: Please see image for reference I aim to display the number inside a circle. What ...

"The art of communication: Websockets bridging the cross-domain

Currently, I am in the process of creating two web applications: The core application, developed using Java with Vert.x, is responsible for receiving data from various other apps and sending it to the client. The client application, built using PHP/JS, i ...

Utilize only API/array information that satisfies a particular condition

I am working with API data that has a specific structure: information random number price amount total random number price amount total Currently, I am using the following code to find the lowest price from the da ...

Ways to insert text into an SVG file

I am currently using vue-svg-map with a USA map. I am trying to display the state code (path.id) on my svg map. Can anyone provide guidance on how to achieve this? <radio-svg-map v-model="selectedLocation" :map="usa" :location-class="getLocation ...

Using Vue to send information to Firebase

I could really use some assistance. Despite my best efforts over the past few days, and despite watching numerous tutorials and consulting various methods in Firebase documentation, I am still unable to make any progress. My current project involves build ...

Is the npm mqtt module continuously running but not performing any tasks?

I'm relatively new to the world of JS, node.js, and npm. I am attempting to incorporate a mqtt broker into a project for one of my classes. To gain a better understanding of how it functions, I installed the mqtt module from npm. However, when I tried ...

Issues with CSS and JS rendering have been observed on a website hosted through BlueHost

Just set up my website with Bluehost and running into issues with CSS and JS not rendering properly. Here's a glimpse of my public_html folder structure: https://i.sstatic.net/VnHFP.png The assets folder includes separate folders for CSS and JS fil ...

Get an array of JSON values using a jQuery function

How can I create a jQuery function that imports a JSON value and returns an array when called? I have written the following function, but it is returning an empty array. The JSON file I am working with is very basic, similar to this example: { "fruit": [ ...