Learn the process of reformatting JSON code solely with ES5

Looking for advice on the best way to reformat JSON code below using only es5. I am not very experienced with json formatting, so any suggestions are welcome.

{
  "success": true,
  "results": [
    {
      "id": "12",
      "base": "263422"
     },
    {
      "id": "15",
      "base": "223322"
    }
}

to:


{
    "success": true,
    "results": [
        {
            "id": 29,
            "bill": [
                {
                    "id": 29,
                    "base": 124122,
                }
            ]
        },
        {
            "id": 33,
            "bill": [
                {
                    "id": 33,
                    "base": 12412232
                }
            ]
        }
    }

Answer №1

If you are searching for a way to reformat the structure without altering the data itself, try using code similar to this:

var jsonData = {
    "status": true,
    "items": [
        {
            "id": "12",
            "quantity": "263422"
        },
        {
            "id": "15",
            "quantity": "223322"
        }
    ]
};

for(var index = 0; index < jsonData.items.length; index++) {
    jsonData.items[index].order = [
        {
            id: jsonData.items[index].id,
            quantity: jsonData.items[index].quantity
        }
    ];

    delete jsonData.items[index].quantity;
}

console.log(JSON.stringify(jsonData, null, 4));

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

Tips for retrieving data in the parent component

Currently, I am utilizing Vue v1.0.28 and vue-resource to interact with my API and fetch the resource data. In this setup, I have a parent component named Role, which includes a child component named InputOptions. The foreach loop within iterates over the ...

How to Convert a String to JSON in Python

I have data in this specific format: "{u'Status': u'Up About an hour', u'Created': 1468874455, u'Image': u'instavote/vote', u'Labels': {u'com.docker.compose.service': u'webapp&apos ...

How can MessagePorts be effectively utilized in electron Js?

What are some real-world applications of using MessagePorts in Electron JS? Why is it necessary instead of just using ipcRenderer.invoke? I haven't been able to identify any practical scenarios where MessagePorts are indispensable. It seems like it&ap ...

Is there a way to verify if the user input matches the data in the database?

Currently, my JavaScript program randomly picks an image of an object from the database and shows it to the user. Each image is saved with the object's name, such as apple.gif. To confirm if the user's input response is correct for the test, I&ap ...

Operating a slider on a web page built with HTML

I am currently working on developing a loan calculator that involves two range sliders interacting with each other to display monthly payments in a label. Here are the specific requirements: Display only 5 values on the "Month" range slider: 12,18,24,30,3 ...

How to eliminate unnecessary space when the expansion panel is opened in material-ui

Is there a way to eliminate the additional space that appears when clicking on the second accordion in material UI? When I open the second accordion, it shifts downward, leaving a gap between it and the first accordion. Any suggestions on how to remove thi ...

The GET method is unable to process the body

I have been utilizing mockoon for creating API simulations. I set up 2 routes with the GET method, each responding with a JSON object. Interestingly, my express app seems to struggle parsing one of the routes. However, the route that includes an array in t ...

What is the best way to access data stored in the state of the store.js within a Vue application?

Currently, I am working on my initial project using Vue.js. The application involves a multi-step form that shares a common header and footer. As the user progresses through each step, the data entered is sent to store.js for storage. However, I have encou ...

ES6 Error: Uncaught TypeError - Unable to call modal function

Looking for assistance with ES6 since I am new to it and could use another set of eyes and expertise. Here is my index.js file where I'm attempting to integrate fullcalendar.io: import $ from 'jquery'; import 'bootstrap'; import ...

Is there a way to verify the presence of data returned by an API?

I am trying to implement a system in my Index.vue where I need to check if my API request returns any data from the fetchData function. Once the data is fetched, I want to return either a boolean value or something else to my Index.vue. Additionally, I wou ...

Retrieve all values for a specific parameter in JArray

When I receive a JArray object from an edit control on the front-end, my goal is to extract and combine all the "text" values. The desired output should be a single string: "Established in 1995, the Elephant Sanctuary in Tennessee has provided ...spans 2 ...

Utilize external functions in evaluated code

After working with a TypeScript file containing the following code: import { functionTest } from './function_test' function runnerFunctionTest() { console.log("Test"); } export class Runner { run(source : string) { eva ...

Sometimes the Select2 placeholder fails to show up consistently

After setting a placeholder for my select2 autocomplete, I noticed that when I move my cursor away from the input field, the placeholder disappears. However, I would like it to always remain visible. Below is the code I am using, and I hope to find a way ...

The _destroy method of the jQuery widget factory is designed to efficiently

I need help creating a timer widget that can start with a specific number of seconds and be reset at any time by initializing it again with a new set of seconds. I have managed to create the timer and make it count down, but now I am facing an issue. My g ...

Adding a CSS link to the header using JavaScript/jQuery

Is there a way to dynamically inject a CSS link located in the middle of an HTML page into the head using JavaScript? <head> ... styles here </head> <body> code <link href='http://fonts.googleapis.com/css?family=Lato:400,300, ...

Encountering an error in Rails when using the form_for method with JSON data: Hash object does

Recently, I made the switch to using redis on my website so that a JSON array is now sent to my views instead of an ActiveRecord array. This involved a lot of necessary conversions such as changing model.attribute to model['attribute']. However, ...

generating a dynamic string array containing particular elements

Given a string "hello @steph the email you requested is [email protected] for user @test" The goal is to transform it into: ['hello ', <a href="">@steph</a>, 'the email you requested is <a href="/cdn-cgi/l/email-protect ...

Unable to create a random number using JavaScript

Looking for a bit of help with this code snippet: <!DOCTYPE html> <html> <head> <title>Test Your Luck Here!</title> <script type="text/javascript"> function myFunction() { var x = Math.floor((Math.random() * 6) +1); doc ...

Technical issue encountered with radio button onchange/onclick event functionality

Is there a way to retrieve the value of a radio button when it is clicked or changed? I'm facing an issue where my code only works for the first radio button and not for the other ones. When I click on the first radio button, it alerts the value succe ...

Is there a reason to not simply reset the connection to the $.ajax?

Ensure that the server is available before loading the scripts. On the client side jQuery(document).ready(function(){ jQuery.ajax({ dataType: "jsonp", timeout: 1000, cache: false, url: "http://xxx/include/xxx.php?q=? ...