Updating JSON values based on a list of keys in JavaScript

I possess an item that delves deep into its structure. For instance:

section: {
     data: {
          x = 4
     }
}

The actual one goes even deeper.

How do I go about updating the x value with a function like this:

const keys = [section, data, x];
const update = (newValue, keys) => {
      // it should look something like this
      // myObjc[section][data][x] = newValue;
}

Answer №1

https://i.sstatic.net/IKujj.png

In my opinion, the solution lies in implementing a deep set value function similar to the following:

const updateValue = (newValue, keys, obj) => {
    for(const key of keys.slice(0,-1))
        obj=obj[key];
    obj[keys[keys.length-1]]=newValue
}

Answer №2

To prevent errors, one can utilize a recursive function

/**
 * Function that securely updates a key within an object to avoid unexpected errors
 * @param obj The target object
 * @param path An Array containing the string representation of the path
 * @param value The new value to be assigned
*/

function secureObjectUpdate(obj, path, value){
  if(path.length === 0){
    throw new Error('Unable to update object without a specified path');
  }
  if(path.length === 1){
    obj[path[0]] = value;
    return;
  }
  if(path.length > 1){
    if(typeof obj[path[0]] === 'undefined'){
      obj[path[0]] = {};
    }
    if (typeof obj[path[0]] !== 'undefined' && typeof obj[path[0]] !== "object") {
      throw new Error('Cannot assign key-value pair to non-object type');
    }
    let unwrapped = obj[path[0]];
    secureObjectUpdate(unwrapped, path.slice(1), value);
  }
}

Answer №3

const object = {section: {data: {  x: 4 }} }

const keyArr = ['section', 'data', 'x'];
const modifyObject = (value, keyArr, obj) => {
      const lastKey = keyArr.reduce((accumulator, currentKey, index) => {
            if (index == keyArr.length - 1) {
                  accumulator[currentKey] = value
            }
            return accumulator[currentKey]
      }, obj)
      obj = lastKey
}

modifyObject(5, keyArr, object)

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 a search filter in Vue.js using a nested for loop

I am currently working with a JSON object that contains nested objects and I need to iterate over them to extract data. Everything is functioning correctly, but now I want to implement a search/filter feature where the search is performed on the second lev ...

Vue.js data does not exhibit reactivity

I am encountering an issue with a non-reactive data object nested inside another object in my Vue.js template. Here is the code snippet: <template> <div> <b-container class="bg-white text-center scrollBehavior" > ...

Transforming a sophisticated nested array containing named values into JSON format

I am facing a challenge with converting an array into JSON format. The array, named classProfiles, has the following structure (seen after inspecting console output): Buildings_clear: Array(0) band1: [Min: 24, Max: 24, Mean: 24, Median: 24, StdDev: 0] ...

Utilize Jquery to dynamically modify the content on a webpage

I am looking to use Tampermonkey in order to reverse the text on a specific website, like BBC News. I have already started working on a script that can replace certain text, but I am facing difficulty in accessing all the text present on the page efficient ...

Utilize jQuery in phantom.js to send an ajax request across domains

I am currently in the process of testing a chrome plugin by emulating a portion of its functionality on phantomjs. My objective for phantom seems quite straightforward, yet I am encountering issues. I aim for it to navigate to a specific webpage and withi ...

VueJS, when used in conjunction with Vuetify, might require an extra loader to handle scoped css

While attempting to compile my VueJS code using webpack, I encountered an error with the following code: <template> <v-app-bar app color="blue" flat height="100px"> <v-img class="mx-2" contain max-height="80" m ...

After the update to the page, the DOM retains the previous element

I'm currently developing a Chrome Extension (no prior knowledge needed for this inquiry...) and I have encountered an issue. Whenever I navigate to a page with a specific domain, a script is executed. This script simply retrieves the value of the attr ...

Retrieving data from a nested JSON array using List<Class> in Flutter

Here is an example of JSON data: { "status": "true", "data": [ { "idpekerjaan": "1", "namapekerjaan": "Apel Pagi / Sore", "subpekerjaan": [ { "idsubpekerjaan": "2", "namasubpekerjaan" ...

What does Angular classify as a watcher?

What qualifies as "watchers" within Angular? Are watchers the only type of monitoring mechanism, or do other Angular elements like ngModel also serve as watchers? Am I overlooking something crucial? For example, do watchers play a role in enabling directi ...

Conceal a div once the content in a separate div has finished loading

After loading an image in slices inside a div, I want to ensure that the entire content is loaded before displaying the div. To achieve this, I am using another div as a mask while the content loads: <div id="prepage" style="position:absolute; left:0px ...

Access the style of the first script tag using document.getElementsByTagName('script')[0].style or simply refer to the style of the document body with document.body.style

Many individuals opt for: document.getElementsByTagName('script')[0].style While others prefer: document.body.style. Are there any notable differences between the two methods? EDIT: Here's an example using the first option: ...

What is the process for configuring my form to automatically send to my email upon clicking the send button?

I found this code snippet on a website and I'm trying to figure out how to make the 'Send!' button redirect users to my email address with their message, name, and email included. Can anyone help me solve this issue? I attempted to add my e ...

OpenAI gym throws an IndexError when attempting to use arrays as indices that are not of integer or boolean type

I've been putting my skills to the test with an OpenAI Gym project lately. While coding to tackle a particular environment, I keep encountering an error stating "IndexError: arrays used as indices must be of integer (or boolean) type", which seems to ...

"Switching a div's visibility when a link is clicked

http://jsfiddle.net/FsCHJ/2/ Currently, when I add another link, it automatically uses the same functionality as the toggle button. What I want is for "Toggle Edit Mode" to toggle a hidden div on and off. I attempted to modify the code from $("a").click(f ...

Guide to selecting an element with a combination of text and a random number using Selenium with JavaScript

<a id="Message4217" class="btn-sm btn-danger Message" data-id="4217"><span class="icon-adjustment icon-trash"></span> Delete</a> The objective is to remove a message base ...

Utilizing JSDoc's "includePattern" for various file formats

Recently, I delved into JSDocs and decided to implement it in my Vue.js project. However, since my project involves multiple file types like .js and .vue, I encountered a syntax error while trying to add them to the "includePattern". Here's the snippe ...

Trigger the React custom hook when the form is submitted

I have developed a custom useFetch hook to handle API requests in various sections of the application. It works smoothly when a component is rendered, but I am facing an issue when trying to make a request upon form submission. An error message pops up say ...

What is the best way to ensure all my borders are uniform in size?

As I work on a JavaScript project that organizes words into blocks based on their size, I encountered an issue with inconsistent border thickness in certain areas. I'm using spans to contain each word, but I can't figure out how to make the borde ...

How can I loop the keyframe animation across various elements of an SVG file simultaneously?

After creating an animation using CSS and SVG, I am experiencing different parts of it animating in and out. My goal is to have the animation start from the top once it's finished. There are multiple keyframes involved since I'm animating variou ...

Progress Indicator on my online platform

I've been attempting to remove a loading bar from my website, but I can't seem to locate it in the site files. I even tried using Google Chrome's inspection tool, but I couldn't pinpoint the loader. Can someone please assist me? Visit ...