Modify the structure of the JSON string

My JSON string is structured like this:

[
    {
        "queryResult": {
            "A": "12-04-2014",
            "B": 1
        }
    },
    {
        "queryResult": {
            "A": "13-04-2014",
            "B": 2
        }
    },
    {
        "queryResult": {
            "A": "14-04-2014",
            "B": 3
        }
    }
]

I need to parse it and transform it into this format

[
    {
        "A": "12-04-2014",
        "B": 1
    },
    {
        "A": "13-04-2014",
        "B": 2
    },
    {
        "A": "14-04-2014",
        "B": 3
    }
]

I currently have a function that accomplishes this task using stringification and parsing, as shown below:

function justAnExample() {
    var jsonData = exampleJSON(); //Retrieves the JSON
    var finalJSON=JSON.stringify(jsonData[0]['queryResult']);
    for (var i = 1; i < jsonData.length; i++) {
        finalJSON = finalJSON+','+JSON.stringify(jsonData[i]['queryResult']);
    }
    return JSON.parse('[' + finalJSON + ']');
}

However, I am curious if there is a more efficient solution that involves working directly with the object notation itself.

P.S: I understand that the term "JSON object" may not be technically accurate, but I am mainly concerned with the JSON notation/format.

Edit

Here is a JS fiddle link for reference:

http://jsfiddle.net/mukilr/uJV54/

Answer №1

Here is a solution:

let data = [
    {
        "queryResponse": {
            "Date": "12-04-2014",
            "Value": 1
        }
    },
    {
        "queryResponse": {
            "Date": "13-04-2014",
            "Value": 2
        }
    },
    {
        "queryResponse": {
            "Date": "14-04-2014",
            "Value": 3
        }
    }
];

let result = [];


for (let j = 0; j < data.length; j++){
result[j] = data[j].queryResponse;
}

View the JS fiddle link

UPDATE You can also view the revised version of your code in this updated JS fiddle

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

Contrasting the lib and es directories

I am seeking clarity on my understanding. I am currently working with a npm package called reactstrap, which is located in the node_modules folder. Within this package, there are 4 folders: dist es lib src I understand that the src folder contains the s ...

Background Patterns on Webpages

My website has a lovely gradient background on the html tag in css, while the body tag showcases a seamless pattern repeating on both the x and y axes. Everything was looking great until I checked the website on an iPad/iPhone in portrait mode, where the ...

Ensure that the floated element stretches to 100% height in order to completely fill the page

I'm working on achieving a height of 100% for the left sidebar so that it fills the page regardless of the size of the "main" div. Currently, it stops at the normal page height and doesn't expand further. Is there any way to make this work as i ...

Is there a way to link the output to the attributes of the constructor in C#?

Developing an interface with the following properties: public interface IDatasource { string Name { get; } string Description { get; } List<GraphPoint> Point { get; set; } } After implementing this interface, I crea ...

Tips for showcasing a restricted amount of data with Angular.js

I've been exploring different ways to limit the results using limitTo, but unfortunately, I'm encountering unexpected issues. Currently, the entire list is being displayed when I only want to show 8 key-value items in a 4/4 block format. You can ...

Why isn't the connect.use() function working in Node.js?

I have been studying and applying examples from a book to learn Node.js. While replicating one of the examples, which involved creating a middleware, I encountered an error when trying to run the JavaScript file. The error message stated "undefined is not ...

The issue arises when a particular JSON string value is processed within the Datapower mpgw service

I am facing a problem with my DataPower service that processes JSON requests and forwards them to a backend service. The issue lies in a particular string field within the JSON request being sent to the DataPower service. Here is an example of a JSON req ...

What is the best method for adding files to JSZip from a remote URL?

Is it possible to load files into a Zip folder from a specified URL? For example: var zip = new JSZip(); zip.file("file.txt", "/site.net/files/file.txt"); Update I am following this example: I attempted the code provided but it was unsuccessful. I do ...

How come it's not possible to modify the text of this button right when the function kicks off?

When I click a button, it triggers a JavaScript function. The first line of code within the function uses jQuery to change the HTML of the button. However, the button's text does not update in the browser until after the entire function has completed, ...

Leveraging JavaScript Functions in HTML

I am having an issue with a JavaScript file containing two similar functions that are executed through an HTML form. While the first function runs smoothly, the second function does not display correctly. It seems like I might be calling or executing the ...

Requires a minimum of two page refreshes to successfully load

Our website is currently hosted on Firebase. However, there seems to be an issue as we have to refresh the website at least twice in order for it to load when visiting www.website.com. Update: We are unsure of what could be causing this problem. W ...

Navigating through directories (including nested ones) containing images in React Native; what's the best way to approach this

I am currently attempting to organize groups of images. Within the directory ./assets, there are several folders structured as follows: ./assets ├── 1x3 │ ├── 1.jpg │ ├── 2.jpg │ └── 3.jpg └── 3x3 ├── 1. ...

Ways to create a URL path that is not case-sensitive in NextJs using JavaScript

I am currently working on a project using NextJs and I have encountered an issue with URL case sensitivity. The paths fetched from an API all start with a capital letter, causing inconsistency in the URLs. For instance, www.mysite.com/About. I would like t ...

Encountering Issues with File Uploads in Express.js with Multer

Currently, I am immersing myself in Node.js through the guidance of a book titled "Web Development with Nodejs and MongoDB." However, I have hit a roadblock when attempting to upload an image using Multer. The code snippet causing me trouble is as follows: ...

Looping through ng-repeats, extracting checked checkbox values in Angular

I am currently dealing with multiple nested ng-repeats in my project, and the third level down consists of a group of checkboxes. Initially, I receive an array of options for these checkboxes, which I handle with the following code snippet: <div class= ...

Having trouble with updating React state? The useEffect hook runs when attempting to change the state, but it seems to have the

Having worked with useEffect and its ability to trigger after a state variable has been updated, I am well-versed in its functionality. I'm currently drafting this post on my phone while away from home. Here's the setup I have: const [dateValue ...

Showing information to several classes using JavaScript

I am currently developing a "Gamebook Engine" that enables users to set a custom username. The user name is extracted from an input element with the id="setUserNameInput" and stored using the function setUserName(). It is then displayed or loaded into an e ...

Difficulty encountered while converting JSON to XML with the force Array feature activated

My current project involves the conversion of XML to JSON and back again, using NewtonSoft.Json (Version=6.0.0.0) in my C# code. To ensure that a single node is treated as an array, I am following the XML structure outlined on the newtonsoft JSON's s ...

Craft a Flawlessly Repeating Sound Experience - Online

I'm facing a challenge in creating a flawless loop of an audio file. However, all the methods I've tried so far have resulted in a noticeable gap between the end and the start. Here are the approaches I experimented with: The first approach inv ...

Webpack is having trouble locating images within Nextjs

When I import static images with no issues using npm run dev, everything runs smoothly. However, when attempting to utilize npm run build or next build, it fails and prevents deployment to Vercel. next info Operating System: Platform: win32 ...