Modify nested JSON in JavaScript, much like how Ruby translations can interpret them (from a list or text)

I have a specific goal in mind. My JSON data is multi-level, structured like this:

 var json = {
   'first_level': {
     'second_level': ['one', 'two']
   },
   'another_first_level': true
 }

and I want to be able to access and modify it in this manner:

load('first_level.second_level');
save('first_level.second_level', ['one', 'two', 'lol']);

Reading the data is straightforward:

 function load(path) {
   var arr = path.split('.');
   var result = json;

   arr.forEach(function(v, i){
     result = result[arr[i]];
   });

   return result;
 }

However, I am unsure how to update the JSON variable using the same string format, especially when the data is deeply nested.. It could be up to 10 levels deep.

Is this even possible?

Here is a codepen with the current example: http://codepen.io/ExClouds/pen/jWBrob?editors=001

Answer №1

Alright, after some trial and error, I finally cracked the code.

Here's the solution:

 function storeData(dataPath, dataValue) {
   var operation = 'json.' + dataPath + '=' + JSON.stringify(dataValue)
   eval(operation);
 }

I've also made an update on CodePen for those who are interested: http://codepen.io/ExClouds/pen/jWBrob?editors=001

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

Exploring the ins and outs of webpage loading speed

I am working on writing JavaScript code that includes a button to open a webpage of my choice. I now want to understand how to detect when the page I called is finished loading. Any suggestions or ideas on this topic? I apologize if my explanation was no ...

Is there a replacement for findIndex in Internet Explorer?

I am currently working on a code snippet for smooth navigation scroll to different sections. var lastId; var topMenu = $(".community-nav"); var topMenuHeight = topMenu.outerHeight() - 19; if(window.matchMedia("(max-width: 768px)").matches) ...

Adding caller information to error stack trace in a Node.js application

I have a function named inner that executes a series of asynchronous operations: function inner(input) { return step1(input) .then(step2) .then(step3) .catch((e) => { throw e }) } I propagate the error from inner so I can m ...

Tips for populating category and subcategory using JSON data

When creating an admin form in React, I want to have a Category and sub-category dropdown selection with options populated from a JSON file (categories.json). The respective sub-categories should be displayed based on the selected category while adding a n ...

Specify that a function is adhering to an interface

Is there a way in Typescript to ensure that a function implements a specific interface? For example: import { BrowserEvents, eventHandler, Event } from './browser-events'; export function setup(){ const browserEvents = new BrowserEvents(); b ...

Issue encountered during unit testing: "Error occurred: 'Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1'"

I am encountering an issue while trying to perform unit testing on a service. The error that I am seeing when running the test is: Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1 at MapSubscriber.project (auth.service ...

What is the best way to execute two JavaScript functions within an inline onclick event?

I am currently working on the following code snippet: <script> function delay (URL) { setTimeout( function() { window.location = URL }, 2000); }</script> And then I have the following within the <body> element: <img src="small_rabbi ...

What is the best way to make my if statement pause until a GET request finishes (GUARD) with the help of Angular?

I am currently working on implementing admin routes for my Angular app, and I have used a role guard to handle this. The code snippet below showcases my implementation: However, I would like the get request to finish executing before the if statement begi ...

In vuex, dynamic modules share common data and do not have unique data

Currently, I am facing an issue with an asynchronous API call that returns an array of objects. After receiving this data, I map it to dynamically registered modules in my store. The process looks something like this: dispatch // prior to this dispatch, ...

Saving Information from Various MongoDB Searches on Node.js

Okay, I believe it would be more helpful if I provide my entire node.js route for you to better understand what I am trying to explain. The issue I am facing is with making multiple queries to my MongoDB database (one for each day). The queries are execut ...

Tips on transforming a Python list to a dictionary with preset key values "default."

I am trying to convert a list of objects into a dictionary where the indices act as the keys list = ['abc', 'dog', 'cat', 'bird',.....] Currently, I am outputting this list as a text file but I would like to transf ...

Adapting CSS styles according to the height of the viewport

Goldman Sachs has an interesting webpage located here. One feature that caught my eye is the header that appears as you scroll down, with squares changing from white to blue based on the section of the page. I'm curious about how they achieved this ef ...

Adding content into a designated position in a document

My challenge is to find the index of user-provided data in order to insert new data at that specific point. I am familiar with array insertion methods, but extracting the index provided by the user is where I'm stuck. My current approach involves filt ...

Experiencing a Type Mismatch Error while extracting Summary data

I'm currently developing a Recipe App, and I've successfully managed to parse the JSON data. However, I've hit a roadblock when it comes to implementing a specific section of each recipe: recipe.json Here is an example snippet from a Recip ...

What is the reason for not encountering an error when reading an array beyond its index limit?

Recently, while working on a pre-existing website with JavaScript code, I made an interesting discovery. I noticed that the code was accessing array items in a unique way: var value = myArray[0, 1]; This seems to be retrieving the second item of the arr ...

What is the best method to prevent next.js components from overlapping one another?

I recently created a website using next.js and noticed an issue in my index.js file. There is a div that houses the main components of the site: class Page extends Component { render() { return ( <div className={styles.container}> ...

Managing JSON data retrieval and manipulation with REST API in Node.js and MongoDB

My technology stack includes Node.js and MongoDB with a rest api. The input data I'm dealing with looks like this: var doc={"name":"ABX", duedate : new Date() } Before sending it to the server, I stringify the data: /rest/update?doc=JSON.s ...

Step-by-Step Guide on Retrieving Filtered Data using React Context API

Currently, I am in the process of developing a dashboard application using React.js, React Context API, and ApexCharts. The app will visualize a 1000-length JSON data on 7-8 different charts, along with 6-7 variable filters. Overview of the App Structure: ...

Tips for dynamically loading images in React with a Collage component

It appears that all the examples I've come across are static in terms of loading images. While the code works, it does not display the divider <div> tag as expected. Instead, the results (images) are shown stacked in the first item of the Collag ...

Having trouble with Node.js POST request; no specific error message displayed

Currently facing a challenge in communicating with an API using nodejs. I've exhausted all possible solutions, including utilizing different request modules and altering the format among other attempts. Here is the code snippet... var request = requ ...