transform a JSON object into a targeted JSON array

Looking to transform a JSON object into an array format, like so:

[ { "name": "Batting" ,"data": [10,20,30,40]} , { "name": "Bowling" ,"data": [10,30,50,70] },{ "name": "Fielding" ,"data": [20,40,50,70]}] 

While I can create JSON objects for each index, I'm struggling with how to put them into a JSON array.

for(var abc in objJSON.yAxis)
{

    seriesValues +=  JSON.stringify({name:abc,data:(objJSON.yAxis)[abc]});
}

Any suggestions on how to achieve this?

Answer №1

Instead of worrying about converting the object to a string, you can easily loop through creating the object.

var data = {"players": { "Michael" : [50, 60, 70], "Jennifer" : [40, 30, 20], "Chris" : [50, 40, 30] } };

var names = Object.keys(data.players),
    playerData = [];
names.forEach(function(name) {
    playerData.push({ "name": name, "scores": data.players[name] });
});

If you ever need to stringify it, just use JSON.stringify(playerData) when necessary.

Answer №2

Almost there:

let arrayValues = [];
for (let item in jsonData.yAxis) {
  arrayValues.push({label: item, values: jsonData.yAxis[item]});
}

This code will create a JavaScript array. If you want to convert it to a JSON string, add:

let jsonString = JSON.stringify(arrayValues);

Answer №3

Convert the array into a string once it has been created.

let newArray = [];

for(let item in jsonObject.xAxis)
{
    newArray.push({item: item, details: jsonObject.xAxis[item]});
}

return JSON.stringify(newArray);

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

For an unknown reason, I am facing difficulties in using the Storage feature from @angular/fire in ANGULAR 16

Recently I started exploring Angular/Fire and decided to test out some of its features by creating a basic app. Firestore and authentication were working smoothly, but when I attempted to include Storage, an error message popped up: ERROR FirebaseError: ...

Loading textures locally using three.js is functioning properly, however, remote loading is not functioning as

I have customized an official example for the Loader object to showcase a specific issue. My goal is to generate a mesh with a texture map that loads before creating the geometry. Currently, I am facing a problem where local files load properly, but remote ...

Exploring JSON data in React applications

Below is the code I am currently working with: export class Highlights extends React.Component { render() { return ( <div> {JSON.stringify(this.props.highlights_data.data)} </div> ) ...

Integrate a post AJAX call into an Angular service for seamless functionality

I have come across an interesting scenario where I have to integrate old ajax code into a new Angular 10 application as per project requirements. Is it possible to directly run the existing ajax calls in the Angular service? Or, is there any node module ...

Retrieving JSON data from an API

As a beginner with Jquery JSON and API's, I am trying to work on hitting an API that returns city names in JSON format. I need to display these city names dynamically on my webpage in a list format. Can someone guide me through this process? If you w ...

Add a new element to an array in a PHP file that will then output the modified

I am faced with a task involving a file that is structured like this: <?php return [ 'key1' => 'value1', 'key2' => 'value2', ... ]; The requirement is to add an additional array entry to this f ...

Iframe navigation tracking technology

Let's say I have an iframe element in my HTML document. <html> <body> This is my webpage <button> Button </button> <iframe src="www.example.com"></iframe> </body> </html> If a user clicks on links wi ...

JavaScript code is functioning properly on Chrome and Internet Explorer, however, it may not be working on FireFox

Despite searching through the console, I am unable to find a solution to this issue. There are two images in play here - one is supposed to appear at specific coordinates while the other should follow the mouse cursor. However, the image intended to track ...

Generate an HTML table dynamically from a PostgreSQL query

I am facing a challenge that may be simple for experienced individuals but is proving to be difficult for me as a newbie. The task at hand involves retrieving JSON data from a database query and displaying it in an HTML table using Node.js, Express, and Po ...

"Converting an object to a JSON string using URLSearchParams: A step-by

I am currently working on a piece of code that retrieves all the input types from a form const form = document.querySelector('form'); const data = new URLSearchParams(new FormData(form).entries()); My main concern is how to convert the above ...

There was an error: "Uncaught TypeError - onPageChange function is not defined for the DataGrid component in Material

I'm struggling to integrate a DataGrid component into my application. While the table renders correctly with the code provided, I encounter an error when clicking on the next page icon - react-dom.development.js:327 Uncaught TypeError: onPageChange is ...

What is the method for utilizing string interpolation in Angular/Typescript in order to retrieve a value from a variable?

I have a variable called demoVars, which is an array of objects with properties var1, var2, and var3. In my component class, I have a variable named selectedVar that holds the name of one of these properties: var1, var2, or var3. I want to dynamically pu ...

Author Names Missing from Book List in Locallibrary Tutorial

After spending several years working on front-end development, I've decided to delve into back-end development to expand my skill set. Following the Basic Node and Express course from FreeCodeCamp Curriculum, I am now following the MDN Express Localli ...

Extract data from an ajax request in an AngularJS directive and send it to the controller

I am currently experimenting with integrating the jQuery fancy tree plugin with Angular. The source data for the tree is fetched through an ajax call within my controller. I am facing a challenge in passing this data to my directive in order to load the tr ...

Exploring the functionality of CodePen's code editor in relation to developing a 2D shooting game

Recently, I created a straightforward 2D shooter game with all the code neatly organized in a single HTML file: (file_gist). When I tested the game in my chrome browser, everything worked flawlessly according to my intentions. However, upon transferring th ...

Show component depending on the lifecycle of another component

I recently encountered a problem with one of my custom components. I developed a "Chargement" Component (Loading in French) for a project I am currently working on. The component is a basic circular spinner with a dark background that indicates to the use ...

Vue components failing to reflect code changes and update accordingly

Initially, the component functions properly, but subsequent changes require me to restart the server in order to see any updates. ...

Convert the columns of pandas into a JSON string

Looking to convert column names and values from a pandas dataframe into a JSON string. For example, if we have the dataset: data= pd.DataFrame({'col1': ['bravo', 'charlie','price'], 'col2': [1, 2, 3],&apos ...

Attempting to access an index of type 'String' on a value of type 'String' is not allowed

Can anyone assist me with this issue I am facing? I want to display a name on a table view cell from an array called postFromFriends. However, when I attempt to access the name in the array, I receive an error stating "Cannot subscript a value of type &apo ...

Looking to dynamically set a background image using data fetched from an API in a ReactJS project

Looking to incorporate a background image from an API response in ReactJS Here is some sample code: useEffect(() => { axios.get(`https://apiaddress=${API_KEY}`) .then(res=>{ console.log(res); setRetrieved(res.data); console.log(retrieved ...