Exploring different ways to navigate JSON data dynamically and efficiently modify it

I have a JSON data structure resembling a map.

var map =  {        
    level1 : {          
            x : {name:'level1 x' , },
            y : {name:'level1 y'}
    },
    level2 : {          
            x : {name:'level2 x'},
            y : {name:'level2 y'}
    }

}

To traverse this data, I am provided with a string representing the path to follow:

"level1 x name" , "level2 y name";

How can I access and manipulate the JSON data based on this string path?

This is what I have attempted so far:

var path = "level1 x name".split(" ");
var pointer = map; // assuming it will take reference of map and change will cause to map also
 for (var i = 0, len = path.length; i < len; i++) {
   if(pointer){
      pointer = pointer[path[i]];
   }else{
     pointer = map[path[i]];
   } 
 }
 pointer = "level1 xx";

console.log(map);

However, the map data does not seem to be changing. How can I iterate through the data and update its values accordingly?

Answer №1

Here is a step-by-step guide to retrieve your desired value:

var result = [data].concat("categoryA subcategoryX".split(" ")).reduce(function(previous, current) {
    return previous[current];
});

console.log(result);

// -> 'subcategoryY'

In JavaScript, arguments are passed by value and not by reference.

To make it easier for you, I have modified the code as per your requirements:

var path = "categoryA subcategoryX".split(" ");
var pointer = data;
for (var index = 0, length = path.length-1; index < length; index++) {
    if(pointer){
        pointer = pointer[path[index]];
    }else{
        pointer = data[path[index]];
    } 
}
pointer[path[path.length-1]] = "subcategoryZ";

console.log(data);

Answer №2

Give this a try! Modify the path variable as needed. It's functioning properly as confirmed in firebug.

var map =  {        
    level1 : {          
            x : {name:'level1 x' , },
            y : {name:'level1 y'}
    },
    level2 : {          
            x : {name:'level2 x'},
            y : {name:'level2 y'}
    }
};
var path = "level1 x name";
var pathInfor = path.split(' ');
var pathLength = pathInfor.length;
//alert(map[pathInfor[0]][pathInfor[1]][pathInfor[2]].name);

for(level in map)
{
    if(level == pathInfor[0]){
       var selLevel = map[level];
        for(xy in selLevel)
        {
           if(xy == pathInfor[1])
           {
                  var selVariable = map[level][xy];
                    for(innerVal in selVariable){
                               if(innerVal == pathInfor[2]){
                               alert(map[level][xy][innerVal]);
                               }
                    }
           }
        }
    }
}

This approach eliminates the need to compare values. To display all JSON values, simply remove the condition.

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

Swap out the div block with a new one

I am currently facing an issue with my JavaScript code. The code is supposed to remove block1 and replace it with block2 when an onclick function is triggered. function buyerclick() { div = document.getElementById('block2'); div.style.displa ...

What is the best way to generate the message dynamically?

I have implemented the react-intl package for translation purposes in my project. Users have the option to choose between Spanish and English languages, with Spanish being the default language. When a user switches to English, all text should be dynamicall ...

NodeJS guide: Enabling cross-domain access for web services

Currently, I am developing a nodejs server and facing the challenge of needing to access additional services through ajax from a different domain. Can anyone provide guidance on how to bypass the cross-domain restriction within nodejs code? Please note th ...

A step-by-step guide on disabling Google Analytics in a Next.js document.js file

Upon a user's initial visit to the website, they are presented with the option to either accept or decline tracking cookies. If the user declines, a cookie is set with the value of false. I am in need of a way to conditionally run the gtag script base ...

Conceal the HTTP status code alert in the Chrome developer console

Currently, I have set up a REST API using Express and for authentication, cookies are being utilized. To retrieve user information, I make a GET request to an endpoint that either returns the user info if logged in or a 401 (Unauthorized) status code if no ...

Trouble with CSS animation when incorporating JavaScript variables from a PHP array

Whenever I use a script to fetch an array of objects from PHP... I successfully display the results on my website by outputting them into Divs. The challenge arises when I introduce CSS animations. The animation only triggers if the variable length excee ...

Scrolling to an element is not possible when it has both position absolute and overflow-x hidden properties

My issue involves animating ng-view with a slideup animation, requiring absolute positioning of elements and overflow-x: hidden to clip the content. However, I need to use the scrollTo element functionality on one sub-page, which doesn't work when bot ...

Enhancing image search functionality through dynamic HTML updates

I need help figuring out how to update the link address for profile pictures on my NHL stats website. Currently, I am using a script to append the image to the body, but I don't know how to properly add the player ID ({{p1_ID}}) to the link and includ ...

The Hydration error is caused by dynamic imports in NextJS v14.2.3

While updating NextJS from v13 to v14, I encountered a Hydration error due to dynamic imports. Is there a way to resolve this issue? const MyComponent = dynamic(() => import('../components/MyComponent')) Is there a fix that allows for both la ...

Is there a way to retrieve the previous value in an input field's onChange event?

I am working with inputs in a React project and have assigned a function to their onChange event. While I have been able to access the current value, I am now looking for a way to retrieve the previous value as well. The reason I need the old value is bec ...

JavaScript form not working on submission

When my form is submitted, a function is called that successfully redirects users on desktop to either the download-confirmation or download-failure page. However, when testing on mobile devices such as iOS and iPad, the redirection does not seem to work. ...

How can I display input only when a checkbox is selected? React with Next.js

I'm trying to figure out how to handle this task, but I'm a bit confused on the approach. I would like to display the promo code field only when the checkbox (I have a promo code) is checked. Additionally, it would be ideal to reveal this field ...

What could be the reason for my React/HTML select element occasionally failing to display the default selected value?

I am currently working on creating a select element in Reactjs/HTML and I am facing an issue with setting a default value based on a component variable. Essentially, the default value of the select should be the id of a component. This is my current imple ...

Implementing Github Oauth2 in a Rails server independent from a chrome extension

Looking to implement Github Oauth2 from my chrome extension, but rather than using chrome.identity.launchWebAuthFlow I want to handle it through my server. This way, I can avoid exposing my client ID and Client Secret in the javascript of the extension. My ...

Chrome and Firefox provide excellent compatibility for running JavaScript, whereas Safari may encounter some issues. Opera's performance with JavaScript can be quirky

Disclaimer: I'm new to web design and development. I have encountered an issue with posting information from a form built on CodeIgniter using jQuery. The form posts successfully in Chrome and Firefox, with the current page automatically reloading. H ...

Tips for utilizing date objects instead of date 'strings' while still obtaining the desired outcome

Below is a schema that I am working with: var MySchema = new Schema ({ event: { full: String, date: String, name: String, } }); To illustrate, here are some examples of the values: event.date = '16/02/20 ...

Code written in JQuery functions correctly when executed within the console, yet encounters issues when located within the script tag or

I'm attempting to build an online drawing tool reminiscent of an Etch-A-Sketch by using a grid of div elements. However, I'm facing an issue where the code responsible for highlighting the boxes when the mouse hovers over them (using the mouseent ...

What is the process for deleting headers in a $http.get call and simultaneously including "application/json" and "text/plain" under the "Accept" header?

I'm relatively new to angularjs and I'm currently working on implementing some new features to an existing Angular JS application. The current API calls are quite intricate so I decided to make a direct call. Below is the code snippet for my new ...

Implementing a JSON array to object conversion in an Express REST API

After conducting a test on a REST API using Postman, the outcome was as follows: { "success": true, "message": "success", "data": [ { "id_buku": 9, "judul_bu ...

Issue with scrolling functionality on dynamically inserted items in jQuery mobile list

I have encountered an issue where the scrolling on my page is not working properly after dynamically adding jQuery mobile list items using jQuery ajax response object. The function responsible for handling AJAX success looks like this: success: function( ...