What is the best way to modify a nested json value when you have the specific key?

I'm working with a nested json object structured like this:

{
  "fontweight": {
    "primary": {
      "weight1": {
        "value": "Regular",
        "type": "fontWeights"
      },
      "weight2": {
        "value": "SemiBold",
        "type": "fontWeights"
      }
    },
  }
}

Imagine I receive a key and value pair, like so:

{
    key: "fontweight.primary.weight1.value",
    value: "Bold"
}

The task at hand is to update the value for the specified key within my nested json structure. How might one go about accomplishing this?

Answer №1

Updating the structure can be achieved in just 4 simple steps.

  1. Begin by splitting

    "fontweight.primary.weight1.value"
    into an array of keys.

    const keys = update.key.split(".");
    
  2. Separate the final key "value" from the others as it is used for assigning values specifically.

    const finalKey = keys.pop();
    
  3. Locate the node/object that requires attribute modification using the keys array with the help of reduce().

    const node = keys.reduce((node, key) => node[key], structure);
    

    If you find the reduce() method confusing, you can also use a loop as shown below:

    let node = structure;
    for (const key of keys) node = node[key];
    
  4. Finally, update the value of the specified node/object using the final key.

    node[finalKey] = update.value;
    

const structure = {
  "fontweight": {
    "primary": {
      "weight1": {
        "value": "Regular",
        "type": "fontWeights"
      },
      "weight2": {
        "value": "SemiBold",
        "type": "fontWeights"
      }
    },
  }
};

const update = {
  key: "fontweight.primary.weight1.value",
  value: "Bold"
};

const keys     = update.key.split(".");
const finalKey = keys.pop();
const node     = keys.reduce((node, key) => node[key], structure);
node[finalKey] = update.value;

console.log(structure);


If there's a possibility that the key points to a non-existent path, consider modifying step 3. Replace node[key] in either the reduce() callback or for...of body with node[key] ??= {}. This will attempt to access key on node, and if it's nullish (null or undefined), assign and return an empty object (check out ??=).

const structure = {};
const update    = { key: "non.existing.key", value: "Hello World!" };

const keys     = update.key.split(".");
const finalKey = keys.pop();
const node     = keys.reduce((node, key) => node[key] ??= {}, structure);
node[finalKey] = update.value;

console.log(structure);

Answer №2

No Need for Lodash Library

If the nested JSON structure does not include an array, you can easily update a JSON value by creating a function called updateValue. This function accepts two parameters: data (the JSON data) and an object containing the key-value pair to be updated. Here is an example of how this function can be used to update a specific value within the JSON:

let data = {
  "fontweight": {
    "primary": {
      "weight1": {
        "value": "Regular",
        "type": "fontWeights"
      },
      "weight2": {
        "value": "SemiBold",
        "type": "fontWeights"
      }
    },
  }
};

let updateValue = (data, obj) => {
  let key = obj.key.split('.');
  let newValue = obj.value;
  let targetObj = data;
  while(key.length > 1) {
    targetObj = targetObj[key[0]]
    key.shift();
  }
  targetObj[key[0]] = newValue;
  return data;
}

data = updateValue(data, 
  {
    key: "fontweight.primary.weight1.value",
    value: "Bold"
  }
);
console.log(data);

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

Transformation of data in Ext JS

Shop: Ext.define('onlineStore.store.market', { model: 'Market', root: 'products', proxy: { type: 'ajax', url: 'http://localhost/onlineStore/data/market.json', reader: { type: ' ...

Search for a specific string within a JSON object using Node.js

Within my JSON file, I need to determine if a specific string exists. For example: let testjson =require('./jsontest.json'); let string= 'abcd'; I want to check if abcd is present within the JSON object. The structure of my JSON file ...

What is the best way to remove table row data fetched from an API within a table?

Can someone assist me with deleting the table tr from the user table, where data is retrieved from an API? I have attempted the code below: $("principleTable").find("tr").hide(); $("#delAgentModal").modal("hide"); ...

Cease the execution within the promise.then block

Embarking on my nodejs journey has been an exciting experience. While I have a background in other programming languages, the concept of promises is new to me. In my nodejs environment, I am using expressjs + sequelize. I'm currently working on setti ...

Is there a way for me to iterate over JSON data within the each tag in a GSP file

I have a piece of code that I need help with: <g:each var="question" in="${confHolder.config.faq}"> <h1>${question.question}</h1> <h1>${question.answer}</h1> </g:each> Within my configuration file, I have the follo ...

Extend the center of the image horizontally

Is there a way to horizontally stretch only the middle section of an image? Let's say I have this specific image: https://i.sstatic.net/pty5A.jpg (source: lawrenceinspections.com) I need the rounded corners to remain unchanged, so simply stretchi ...

Discovering the 3D coordinates of a point that is perpendicular to the midpoint of a line

(I am working with Javascript/Typescript and Three.js) Given two vectors, let's say {x:1, y:3, z:5} and {x:7, y:8, z:10}, I have a direct straight line connecting them. At the midpoint of this line, envision a disc with a radius of 1 that is perpend ...

Using jQuery to restrict the number of checked checkboxes based on a selected value - Here's how!

How can I restrict the number of checkboxes that can be checked based on the selected option from a dropdown menu? For example, selecting 'option1' should allow only 1 checkbox to be checked, 'option2' should allow 2 checkboxes, and so ...

Decoding an inserted JSON object in Android application

Apologies for any language barrier. I am attempting to parse the inserted JSON data, using the following example: { "myTable": { "1": { "type": "1", "category": "1", "body": { "2": { ...

Error when parsing JSON due to the presence of backslashes within the serialized object

When trying to call a server side function and parse the response in client side using JavaScript and Ajax, I encountered a parse error. It seems that the issue lies with the backslash that the JavaScriptSerializer adds to serialize the object. The respons ...

Using shortcode to enhance wordpress post content

I am trying to implement a feature similar to the one found at http://jsfiddle.net/theimaginative/gA63t/ within a wordpress post. I have attempted to create a shortcode for inserting this into a post, but I am encountering difficulties. While I have been s ...

Having trouble locating an external Javascript file in a Node.JS/Express app with Jade template?

In my Node.JS/Express app, I am using the Jade template engine. The issue arises when trying to reference a server-side Javascript file named common_routines. Despite placing the Javascript file in the directory above my views directory and referencing it ...

Retrieving Information from Multiple APIs Simultaneously

I'm currently integrating AngularJS into my project: var retrieveApi = function(){ $http.get(link) .then(function(response) {$scope.data = response.data.api}); } However, I am faced with a new challenge this time. I need to retrieve data ...

The functionality of enabling and disabling dynamic behavior in AngularJs is not functioning as anticipated

As a newcomer to AngularJS, I may have some basic questions. I am currently working on implementing dynamic behavior for a button click event, but it's not functioning as expected. Could this be due to an issue with scope? Below is my HTML code: < ...

What is the best way to transform Json into XML using Scala?

I am attempting to transform a JSON value: [ { "msg": "Hiiiiii", "name": "Ruchirrrr" }, { "msg": "Holaaa Amigo", "name": "Pablo" }, { ...

Different Angular 2 components are resolved by routes

Consider this scenario: Upon navigating to the URL /product/123, the goal is to display the ProductComponent. This is how it's currently configured: RouterModule.forRoot([ { path: 'product/:productId', ...

Are there any JavaScript tools for adding notes to text?

I’ve searched online but haven’t had any luck. Is there a tool available that allows for annotating text selections, even those that overlap? The scenario is that multiple users will be given the same text and need to annotate different selections in ...

Apply a class to each consecutive element following the current one until reaching a child element with a

My goal is to apply a "bg-info" class using jQuery to all rows (tr) that come after odd rows with a child element of "test". The "bg-info" class should be removed when a row with a child element of "test" is encountered, and then re-applied when the next o ...

Are you experiencing problems with JSON formatting?

Currently, I am facing an issue with populating an HTML table using JSON data. The problem arises when I try to populate the table with the JSON data that was provided to me. After careful examination, I suspect that the issue might lie in the formatting o ...

Creating a single endpoint in Django Rest Framework to link a ForeignKey object with a post object

model.py class PostAdvertisment(models.Model): # post=models.ForeignKey(Post,on_delete=models.CASCADE,null=True,blank=True) created_at=models.DateTimeField(auto_now_add=True) title=models.CharField(max_length=255,null=True,blank=True) url= ...