What is the best way to utilize a delimited string for finding and making changes to a specific object key no matter how deep it

This is a challenge that I'm facing in solving a problem. I want my users to be able to do the following:

  1. Point to any key of an object with any depth using a string representation of the "path";
  2. Ensure that each step of the "path" exists; and
  3. Implement CRUD-like functionality.

I am able to validate each key, but I am struggling on how to use the path without resorting to using the eval() function, which is not safe when dealing with user input. Here is where I currently stand:

const SEP = "/" //this value is dynamically set by the server,
MyObjInterface = function() {
    this.params = {};
    this.response = {};

    //some initialization code here...and now for the question.
    
    this.updateOb= function(path, value ) {
        path = path.replace('\\' + DS,"$DIRECTORY_SEPARATOR").split(DS);

        for (var i = 0; i < path.length; i++) {
            path[i].replace("$DIRECTORY_SEPARATOR",DS);
        }

        if (typeof(path) != "object" || path.length < 3) { 
            throw "Could not create rset representation: path is either incorrectly formatted or incomplete."
        }

        var invalidPath = false;
        var searchContext = path[0] === "params" ? this.params : this.response;
        for (var i = 1; i < path.length - 1; i++) {
            if (invalidPath) { throw "No key found in rset at provided path: [" + path[i] + "]."; }

            if (i === path.length - 1) {
                searchContext[path[1]] = value;
                return true;
            }
            if (path[i] in searchContext) {
                searchContext = searchContext[path[i]];
            } else {
                invalidPath = true;
            }

        }
    }
};

Answer №1

To tackle this problem, the approach is to break down the path into individual components and then recursively navigate through the tree structure.

Due to my limited knowledge in JavaScript, I will provide pseudocode.

path = "go.down.three";
listOfElements = breakPathIntoParts(path); // Now listOfElement = ["go", "down", "three"];
myObj = assignValueToObject(myObj, listOfElement, "I'm a value");

function assignValueToObject(obj, listOfElements, value) {
    var firstPart = removeLastElement(listOfElements); // extract and delete the top element from the stack
    if (length(listOfElements) == 0) { // reaching the last element of the path, assign the value
        obj[firstPart] = value;
        return obj;
    } else {
        // check if the property already exists
        var firstValue = obj[firstPart];
        if (firstValue == null) {
            firstValue = new Object();
            obj[firstPart] = firstValue;
        }
        obj[firstPart] = assignValueToObject(firstValue, listOfElement, value);
    }
}

Admittedly, my understanding of JS is lacking (to the extent that I struggle with spelling 'JavaScript'). Consequently, this code remains untested.

Nonetheless, a methodology resembling this one should address your needs. Gradually progress through each component of the path.

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

Are there any methods to utilize Zod for validating that a number contains a maximum of two decimal places?

How can I ensure that a numeric property in my object has only up to 2 decimal digits? For example: 1 // acceptable 1.1 // acceptable 1.11 // acceptable 1.111 // not acceptable Is there a method to achieve this? I checked Zod's documentation and sea ...

React does not automatically re-render components created with the built-in function

I'm facing some confusion with the behavior in my code: I've created a component that should function as a menu using MaterialUI. The idea is that when a button in the menu is clicked, it becomes "active" and visually reflects this change by set ...

What methods can I use to integrate Cheerio with CSS Manipulation?

I've been working on a web scraping project using axios, cheerio, and express. However, every time I attempt to run the project, it encounters errors. For testing purposes, I am using a test page from my friend's website. Here is the code snippe ...

Increase the div id using jQuery

I've got this code snippet here and, oh boy, am I a newbie. How can I increase the number in the div using a jQuery script? if($res >= 1){ $i=1; while($row = mysqli_fetch_array($qry)){ echo "<div clas ...

Dynamic HTML DOM element name changes

One thing I'm considering is the process of dynamically changing element names in the DOM with JavaScript or jQuery when adding or removing child elements. For instance, if I decide to delete the second text box from a form that originally has three t ...

Upon loading the page, I encountered an issue with the 'errors' variable in my ejs template, resulting in an 'undefined' error

When I load my page, I encounter an 'undefined' error with my 'errors' variable in the ejs template. The ejs template I have is for a contact form and it includes code to display errors as flash messages on the page if the form is inco ...

Using jQuery to call a function in processing.js from JavaScript or jQuery

I have set up an application that needs to call a processing.js function, but I am having trouble accessing the processing instance. Here is my setup - in my HTML, I have a link that, when clicked, should trigger the processing function: <div id="wrapp ...

When a ng-model is added, the input value disappears

i am currently working on a form that contains angular values. <tr ng-repeat="alldata in c.da"> <td>{{alldata.id}}</td> <td><input type="text" class="form-control" value="{{alldata.name}}" ...

Console command to change paragraph tag color---Modifying the color

I am attempting to change the color of all paragraph tags on a webpage to white by utilizing the console. My initial attempt was: document.p.style.color = 'white'; However, this method did not have the desired effect. Interestingly, I have had s ...

Comparing arrays in R based on non-matching dimensions

Dealing with two arrays in R. array1[x,y] array2[x,y,t] I am looking to calculate an array3[x,y] which stores the index 't' that represents the smallest difference between array2 and array1. These arrays were imported from netcdf files. In orde ...

Blending Angular5 and AngularJS in Polymer

We are considering launching two new projects - one using Angular 5 and the other utilizing Polymer. The second project is intended to serve as a component library for reuse in not only the Angular 5 project but also in other AngularJS projects. After res ...

Error: Unexpected token found in jQuery code execution

I'm encountering an error that says: Uncaught SyntaxError: Unexpected Token Here is the code snippet where the error occurs: $(document).ready(function(){ $(".cartsummary .showcartsumm").click(function() { $(".cartsummary .cartitems").show(); ...

How to choose the option in one select box based on the selection in another, and vice versa

How can I dynamically select options in one select box based on the selection of another, and vice versa? I am using Ajax to redirect to a query page. while($result = mysql_fetch_assoc($query1)) { echo "<option value=".$result['username' ...

Using JavaScript to retrieve comma-separated values depending on a specific condition

Hey there, I am encountering a problem with filtering out values from an array of objects. Essentially, I have an array of objects const arr = [ { "id": null, "name": null, "role": "Authorized ...

Unit testing in Angular JS is crucial, especially when testing functions in services that do not return any values

Apologies if this has been asked before, but I couldn't find a solution to my issue. I need to create tests for a service within an Angular JS application. The main function of the service returns and is used as an external method. There are also a ...

Can you provide an explanation of what the 'attribution' key does in the tomTomMap.addSource() function?

I came across a solution on how to integrate the openweathermap layer into a tom-tom map: tomTomMap.addSource('owm_source', { type: 'raster', tiles: [ 'https://tile.openweathermap.org/map/clouds_new/{1}/{51}/{20}.png? ...

Rotating elements with timed jQuery

I'm having trouble getting the selector to rotate at different intervals. I attempted using an if/else statement to make the first rotation occur after 3 seconds and subsequent rotations occur after 30 seconds. Unfortunately, it's rotating every ...

Complete circular gauge in Ionic

Encountering an issue when attempting to incorporate a complete circle Gauge/Gage in Ionic, as the gauge fails to display. Has anyone managed to successfully include a full circle Gauge in Ionic similar to this: https://i.sstatic.net/OKcpD.jpg Came acro ...

Click event for nodes in a d3js tree layout

My current project involves utilizing the d3js tree layout to showcase an interactive tree structure on the screen. Is there a comprehensive tutorial or detailed documentation available for effectively implementing the d3js tree layout? Furthermore, I ai ...

Generating a new Blob through assembling MediaRecorder blob sections leads to a blank Blob

I’ve encountered a peculiar issue with the new Blob constructor. My code returns an array of Blobs from the MediaRecorder: https://i.sstatic.net/X8Z7c.png However, when trying to work with this blob in my code, calling new Blob(audioChunks) results in ...