Changing an array in JavaScript to suit different needs

Here is an example of a JSON array:

[ 
     {category: 'Category 1', data: [ {date: '01/04/2021', value: 10}, {date: '01/03/2021', value: 20}, {date: '01/02/2021', value: 5}] },
     {category: 'Category 2', data: [ {date: '01/04/2021', value: 8}, {date: '01/03/2021', value: 2}, {date: '01/02/2021', value: 15}] },
     {category: 'Category 3', data: [ {date: '01/04/2021', value: 7}, {date: '01/03/2021', value: 1}, {date: '01/02/2021', value: 5}] }
]

Could you please help me convert this JSON array into a different format using JavaScript or TypeScript?

[
     {category: 'Category 1', 'Apr 2021' : 10, 'Mar 2021' : 20, 'Feb 2021': 5},
     {category: 'Category 2', 'Apr 2021' : 8, 'Mar 2021' : 2, 'Feb 2021': 15},
     {category: 'Category 3', 'Apr 2021' : 7, 'Mar 2021' : 1, 'Feb 2021': 5}
]

Answer №1

Here is a method to achieve the desired outcome:

datas.map(data => {
  const updatedData = {
    category: data.category
  };
    
  data.data.forEach(entry => updatedData[entry.date] = entry.value);
 
  return updatedData;
});

Answer №2

In case you are facing an issue with converting the value to a property, you can achieve it in the following manner (For details on date formatting, refer to this guide on formatting a JavaScript date):

[ 
  {category: 'Category 1', data: [ {date: '01/04/2021', value: 10}, {date: '01/03/2021', value: 20}, {date: '01/02/2021', value: 5}] },
  {category: 'Category 2', data: [ {date: '01/04/2021', value: 8}, {date: '01/03/2021', value: 2}, {date: '01/02/2021', value: 15}] },
  {category: 'Category 3', data: [ {date: '01/04/2021', value: 7}, {date: '01/03/2021', value: 1}, {date: '01/02/2021', value: 5}] }
].map(x=> {return {category: x.category, [x.data[0].date.toString()] : x.data[0].value}})

https://i.sstatic.net/JjCDX.png

Answer №3

Utilize Array#map to generate a fresh array using this method.

const yourArray = [{category:'Category 1',data:[{date:'01/04/2021',value:10},{date:'01/03/2021',value:20},{date:'01/02/2021',value:5}]},{category:'Category 2',data:[{date:'01/04/2021',value:8},{date:'01/03/2021',value:2},{date:'01/02/2021',value:15}]},{category:'Category 3',data:[{date:'01/04/2021',value:7},{date:'01/03/2021',value:1},{date:'01/02/2021',value:5}]}];

const result = yourArray.map(({category, data}) => {
  const otherProps = data.reduce((acc, {date, value}) => {
    acc[date] = value;
    return acc;
  }, {});
  return {category, ...otherProps};
});
console.log(result);

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

Passing in additional custom post data alongside serializing with jQuery

function MakeHttpRequest( args ) { var dataToSend = "?" + $("form[name=" + args.formName + "]").serialize(); $.ajax({ type: "POST", url: args.url + dataToSend, data: { request: args.request }, su ...

Click on the nearest Details element to reveal its content

Is there a way to create a button that can open the nearest details element (located above the button) without relying on an ID? I've experimented with different versions of the code below and scoured through various discussions, but I haven't be ...

Ways to loop through an array of daytime values and exhibit just the records for the current week

ng-repeat="day in task.DailyWorks | limitTo : weekdays.length: weekStart" This iteration process enables me to showcase the daily work records in a structured format within the table columns. The feature allows for seamless navigation between different we ...

Issues with comparing dates

I'm attempting to compare two different dates: Start Date Thursday, October 29th, 2015 at 6:00 PM GMT End Date Friday, October 30th, 2015 at 12:00 AM GMT Simply put, if(end > start) { alert('It works'); } else { alert(&apo ...

Utilizing data from an external JavaScript file in an Express application

I am currently developing an application using Node.js Express, where I need to pass some data from Express and utilize it in an external JavaScript file. Below is my app.js: const express=require('express'); const path=require('path&apos ...

Converting a specific type of string into an array with keys in PHP: the ultimate guide

I need to transform a specific string into an array in PHP. The string looks like this: string(11) "2=OK, 3=OK" The desired output should be an array with keys like this: array ( [2] => Ok [3] => Ok ) I usually rely on explode() and str_split( ...

Despite the unconsumedBufferLength being 0, DataReader.loadAsync is still being completed

Working on UWP WinRT, I'm dealing with JSON stream consumption using the following code: async function connect() { let stream: MSStream; return new CancellableContext<void>( async (context) => { stream ...

Ever wonder what goes on behind the scenes when you press a button before the Javascript method is carried out

My web application is built using ASP.NET MVC 4, jQuery, and Telerik's Kendo controls. Within my webpage, I have the following code snippet: <input id="cmdSaveToFile" title="Save To File" class="button" type="button" value="Save To File" onclick= ...

Component in Next Js fails to pass props when using getInitialProps

I am facing some challenges with Next Js and could really use some assistance. We have a component where I am utilizing "getInitialProps" to pass props to it during the server-side rendering process. However, no matter what I try, the props do not seem to ...

Creating dynamic input forms in PHP

New to PHP and seeking guidance! I'm in the process of creating a photography website and encountering an issue with a specific page. Essentially, I need this page to display a form with a varying number of inputs. The goal is to have a dynamic visua ...

What causes an error when attempting to add a new user to the database?

Currently, I am delving into the world of Mongodb. To kick things off, I initiated by executing npm install --save mongoose uuid within the confines of Terminal. The primary objective of my project revolves around storing user information in the database. ...

Can you tell me the title of this pointer?

When utilizing the drag function in the RC-tree, a specific cursor is displayed. I am interested in using this cursor in another dragzone on my website, but I am uncertain of its name. This same cursor also appears when dragging highlighted text into the b ...

An instructional HTML/JS dialogue for a linked page

On my website, there is a link that, when clicked, opens a new tab with a page that I don't control. I want to guide the user on what to do next after they are redirected to this new page ("Now please press the green button on this page"). Ideally, I ...

Leveraging Firebase Dynamic Links through JavaScript

Currently exploring options for implementing Dynamic Links. Firebase Dynamic Links seem promising, but the lack of support for Cordova/ ionic apps is concerning. Is there any plan to add this in the future? Are there any other alternatives that you would ...

The updating of Angular 2 CLI variables does not occur

As a complete newcomer to Angular 2, I recently attempted to start my first project using the Angular CLI. Unfortunately, I encountered some issues. It seems that the variables in my views are not updating as expected. I followed the typical steps: ng n ...

Using numerous textures for a single mesh in THREE.js

I am working with an OBJ file that utilizes four textures. The UV coordinates in the file range from (0, 0) to (2, 2), where (0.5, 0.5) corresponds to a coordinate in the first texture, (0.5, 1.5) is a UV coordinate in the second texture, (1.5, 0.5) repres ...

Transform a fabricjs canvas into a base64 encoded image

I am attempting to transmit a canvas as an image to my server in base64 format. While Fabricjs provides options such as canvas.toSVG() or canvas.toDataURL({format: 'image/png'}) to convert the canvas to an image, the output I see in my console ap ...

Encountering an issue while attempting to generate a dialog popup with jQuery

As a beginner in jQuery, I am attempting to implement a popup dialog box for users in case of an error. However, I'm encountering issues with the following jQuery code: <script type="text/javascript"> $(document).ready(function() { var $dia ...

Using InnerHTML in Javascript within the Quasar/VueJS framework is unsupported

I am looking to dynamically create tables based on the items inside the 'counts' array below. The number of tables and their contents can change. Here is my divContainer, where the innerHTML will be appended: <div id="divContainer" style="pa ...

The driver instance that has forked will never cease

Issues arise when attempting to run multiple browser windows in Protractor. The code snippet being tested is as follows: I create a new browser instance to perform certain tests. When input is entered into the original browser, it should not affect the ne ...