Update the JSON object and store the changes

I have a json array object that requires modification and saving the updated version to a variable.

The original json object is:

var json = [ 
{ 
  "Name": "March-2016", 
  "Elements": [ 
    { 
      "Name": "aa", 
      "Elements": [ 
        { 
         "Name": "ss", 
          "Data": { 
            "Test1": [ 
              22
            ], 
            "Test2": [ 
              33 
            ],
            "Test3": [ 
              44
            ],
            "Test4": [ 
              55
            ]
          } 
        },
        { 
          "Name": "ssee", 
           "Data": { 
             "Test12": [ 
               222
             ], 
             "Test22": [ 
               3322 
             ],
             "Test32": [ 
               445
             ],
             "Test42": [ 
               553
             ]
           } 
         }  
      ] 
    } 
  ] 
} 

;

The modified version should be:

 var json = [ 
{ 
  "Name": "March-2016", 
  "Elements": [ 
    { 
      "Name": "aa", 
      "Elements": [ 
        { 
         "category": "ss", 
            "Test1": 22, 
            "Test2": 33 ,
            "Test3":44,
            "Test4": 55 
        },
        { 
          "category": "ssee", 
          "Test12": 222, 
          "Test22": 3322 ,
          "Test32":445,
          "Test42": 553 
         }  
      ] 
    } 
  ] 
} 

;

I am trying to achieve this using the saveJson method but encountering issues. Here's the method:

var saveJson = function(arr) {
var nameValuePairs = [];
for (var i = 0, len = arr.length; i < len; i++) {
  var item = arr[i];
  if (item.Data) {
    var newvar = {
       category : item.Name
     }
     newvar[Object.keys(item.Data)] = Object.values(item.Data);
     item = newvar

  }

  if (item.Elements) {
    nameValuePairs = nameValuePairs.concat(saveJson(item.Elements));
  }
}
return arr;
};

I need assistance in making this conversion dynamic as I anticipate working with larger json arrays than the sample provided. Thank you for your help in advance.

Answer №1

The initial data structure is quite chaotic, however, by carefully navigating through it and extracting the desired values, you can tidy it up. The following script modifies the json object directly:

json.forEach(entry => {
  entry.Elements.forEach(outerElement => {
      outerElement.Elements = outerElement.Elements.map(subItem =>{
          let tempObj =  {category: subItem.Name}
          Object.keys(subItem.Data).forEach(key => {
              tempObj[key] = subItem.Data[key][0]
          })
          return tempObj
      })
   })
})

The updated json should now resemble this:

[{
    "Name":"March-2016",
    "Elements":[
        {
            "Name":"aa",
            "Elements":[
                {
                    "category":"ss",
                    "Test1":22,
                    "Test2":33,
                    "Test3":44,
                    "Test4":55
                },
                {
                    "category":"ssee",
                    "Test1e":224,
                    "Test2e":334,
                    "Test3e":443,
                    "Test4e":554
                }
            ]
        }
    ]
}]

Answer №2

Employing destructuring assignment allows for extracting specific property values from an object

{
  const {Title:sections, Info:{Description:[Description]}} = jsonResponse[0].Objects[0].Objects[0];
  jsonResponse[0].Objects[0].Objects[0] = {sections, Description};
}

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

JavaScript appends a backslash character to a CSS class

I am attempting to populate index.html with the contents from an array using a JavaScript loop. However, I am encountering an issue where a CSS class for picture formatting is displaying some odd characters when rendered in the latest version of Firefox. ...

The client side script "/socket.io/socket.io.js" was not located, therefore the Express-generator project was used instead

I have been working on integrating the "chat-example" from Socket.IO's official website into an Express-generator generated project while keeping the structure of the project intact. I have made minimal changes to the code to fit it into the existing ...

Rearrange the position of an element within an array

I'm struggling to find a solution for rearranging elements within an array. Consider the following: var array = [ 'a', 'b', 'c', 'd', 'e']; How can I create a function that moves the element 'd&a ...

Creating an ImmutableJS Record with custom types: A step-by-step guide

Is there a way to make ImmutableJS Records throw runtime exceptions if fields are missing instead of needing default values? ...

Fetching post data from an HTML form in Node.js using Express 4: A comprehensive guide

This is the content of my main.js file: var express = require("express"); var app = express(); var bodyParser = require("body-parser"); var userAPI = express.Router(); app.use(express.static(__dirname + '/public')); app.use( bodyParser.json() ) ...

"Troubleshooting: Unable to Trigger jQuery Click Event Using Class Selector

I have two separate lists with different classes, <li><a href='#' class="cls1" name="X">blah</a></li> <!-- Click to load a cls2 item --> <li><a href='#' class="cls1" name="Y">blah</a>< ...

The JSON file overwrites entire objects instead of targeting individual ones

Is there a way to update just one specific object in a JSON file without affecting the rest? I've implemented a put request on the front-end using axios to send data to the back-end for processing. However, the current functionality replaces all obje ...

What are the steps for manipulating JSON data in a string retrieved using Axios?

Issue with Parsing Key Values I have a frontend HTML file where I am passing a variable using axios for API communication. In my app.js route, when receiving the data, all values are present in keys but the key values are empty. This indicates a need to p ...

What is the best way to create a regex that can recursively assign string values to an array?

I am looking to extract variables from a string that resembles a shortcode, and store these variables in an array. The text provided is: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur pulvinar erat quis aliquet pulvinar. Vivamus eg ...

Switch up the animation based on the state in AngularJS

In my AngularJS application, I have implemented CSS animations for transitioning between states. The animations involve sliding content from left to right with specific timings and transforms. .content.ng-enter, .content.ng-leave { -webkit-animation-t ...

Activate dynamic form fields using Ajax

Consider a scenario where the code looks like this: <div id="stuff<? echo $dynID; ?>" class="bla"> <form id="myform<? echo $dynID; ?> " action="bla.php"> <input name="iname<? echo $dynID; ?>" value="<? echo $row[1] ...

assigning a value of undefined to the selected option in AngularJS

How can I use angularjs ng-options and ng-model directives to set the select option and detect when the dropdown option is selected or changed? I want to include an extra empty option so that the user can deselect it, and in that case, I want the value in ...

Constructing Browserify with dependencies containing require statements within a try-catch block

When attempting to integrate timbre.js (npm version) with Browserify, I encountered an issue where require statements for optional dependencies were enclosed in a try statement (check the source here). This resulted in a browserify build error displaying: ...

Encountering a 'Exception Unhandled' error in C# when attempting to parse JSON data

I am currently working on extracting data from a JSON file and updating the text of a label in C#. However, I have encountered an 'Exception Unhandled' error: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'The best overloaded method ...

The console.log() function does not accurately display the true value

While looping through a list and using a @click function to update other elements, I have encountered an issue with the index values bound to selectedFixtures. Each time I click on an element, it initially prints out [], and then on subsequent clicks, it ...

Error: Issue transferring data to controller from Ng-Style

Currently, I am developing an application using Ionic and AngularJS. In this project, I am using ng-repeat to populate the results and want to display different colors based on certain criteria. Initially, I managed to achieve this using inline ng-style c ...

What can be used instead of makeStyles in Material UI version 5?

My journey with Material UI version 5 has just begun. In the past, I would utilize makestyles to incorporate my custom theme's styles; however, it appears that this method no longer works in v.5. Instead of relying on {createMuiTheme}, I have shifted ...

Activate UpdatePanel upon hovering the mouse cursor over it (displayed as a tooltip)

In order to provide users with additional information, such as a tooltip, on items within a RadioButtonList, I am looking to display about 500 - 600 characters of info. Currently, I am updating a PanelUpdate when a user selects an item in the RadioButton ...

ESLint is reporting that TopBarClass is missing from the file './TopBar' while trying to import it as a named module

Currently, I am in the process of creating a React application using JSX and encountering an error from ESLint: ESLint: TopBarClass not found in './TopBar'(import/named) This is the content of the file that is triggering the error: import Reac ...

Dynamically loading JSON information into a DIV using AJAX requests

I have a list of Events in JSON format that I want to display. Below is the JSON data: [{ "event_id": "1636", "event_name": "Nitelounge supported by Mo\u00ebt &amp; Chandon", "event_start_date": "2013-05-27", "event_start_time": " ...