Transforming the JSON structure in JavaScript

Is there a way to transform the JSON format below into the desired output?

[
  {
    "type": "System Usability Score",
    "score": 74,
    "date": "2020-03-19T18:30:00.000+0000"
  },
  {
    "type": "System Usability Score",
    "score": 87,
    "date": "2020-03-31T18:30:00.000+0000"
  }
]

Desired Output:

[
  {
    "name": "System Usability Score",
    "series": [
      {
        "name": "2020-03-19T18:30:00.000+0000",
        "value": 74
      },
      {
        "name": "2020-03-31T18:30:00.000+0000",
        "value": 87
      }
    ]
  }
]

Would appreciate some assistance with this, thank you!

Answer №1

Give this approach a try using Array.prototype.reduce

"use strict";

const input = [
  {
    "type": "System Usability Score",
    "score": 74,
    "date": "2020-03-19T18:30:00.000+0000"
  },
  {
    "type": "Net Promoter Score",
    "score": 89,
    "date": "2020-03-23T18:30:00.000+0000"
  },
  {
    "type": "Net Promoter Score",
    "score": 78,
    "date": "2020-03-25T18:30:00.000+0000"
  },
  {
    "type": "System Usability Score",
    "score": 87,
    "date": "2020-03-31T18:30:00.000+0000"
  }
]


var output = input.reduce((collect, {type, score, date}) => {
  let el, series
  if (el = collect.find(({name}) => name === type)) {
    series = el.series
  } else  {
    series = collect[collect.push({name: type, series: []}) - 1].series
  }
  series.push({name: date, value: score})
  return collect
}, [])

console.log(output)

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

Creating a nested set of directives by iterating over an array within an AngularJS directive

When working inside an angularJS directive, I am attempting to iterate through an array and create a nested list of directives based on the values. The current version of the directive is as follows: Type Directive .directive("type", function($compil ...

Elegant switch in jQuery

I am trying to use jQuery to create an animated toggle button. The toggle function is working correctly, but I am having trouble adjusting the speed and smoothness of the animation. After researching different methods and attempting to modify the values i ...

Traverse an array of nested objects in Firebase JSON notation

Currently, I am utilizing firebase4j, a Java library for Firebase. Although I understand that it is more optimal to use Node.js, I wanted to experiment with Java for this project. Within my database, I am required to store the URLs of images along with var ...

Although responseText functions properly, responseXML remains constantly null

I've searched through all available answers here and still can't find a solution. I'm confident that I haven't overlooked anything obvious. My issue involves loading map markers based on latitude and longitude coordinates. The problem ...

Navigating objects in an Array in React

const [formData, setFormData] = useState( { "student": [ { name:"", age: "" } ] } ); How can I update the state object inside an array and pass ...

Choose a specific value from a drop-down menu

Looking for a solution with this piece of code: $('#Queue_QActionID').change(function () { if ($(this).val() == '501' || $(this).val() == '502' || $(this).val() == '503' || $(this).val() == '504' || $( ...

Unable to invoke JS function in Drupal 5 file

In my current project using Drupal 5, I have a specific .js file that is included using the code: drupal_add_js(drupal_get_path('module','MTM')."/include/JS_form.js"); Additionally, there is an element on the page: <a onclick="MTM ...

The functionality of $(this).data seems to be malfunctioning

I've spent the last couple of hours doing research but still can't seem to figure this out. I'm using ajax to load content, and for some reason $(this).data is not working as expected. If I replace this with the actual class, the content lo ...

What is the best way to showcase multiple selected values in a div using jQuery?

Is there a way to use jquery to populate an empty div with the values selected from a multi-select dropdown? How can I achieve this in the context of the provided code snippet? <select multiple data-style="bg-white rounded-pill px-4 py-3 shadow-sm" c ...

retrieve HTML content from XML document using the correct user input

I am looking to create a section of an HTML page that can only be accessed through a specific code. The page is coded using pure HTML, CSS, and JavaScript. Here is the proposed logic: User inputs a string into a form Upon clicking the submit button, an ...

retrieve the value of a specific key using JSON stringify

[{"displayorder":"1","menuname":"DashBoard","menuid":"5","menuurl":"dashboard.php"},{"displayorder":"3","menuname":"Accounting Module","menuid":"3","menuurl":""},{"displayorder":"4","menuname":"My Profile","menuid":"4","menuurl":"myprofile.php"},{"displayo ...

Analyze the JSON feedback

In Java, I am attempting to parse the following JSON response and retrieve the "message" and "WORKORDERID" data. { "operation": { "result": { "message": " successfully.", "status": "Success" }, "Details" ...

Tips for choosing option values from the browser console in Angular

Is there a way to choose one of the list values directly from the browser console? I appreciate any assistance provided <select style="width: 100%" id="Select1" class="css-dropdowns ng-not-empty ng-dirty ng-valid ng-valid-required n ...

Newly inserted table columns aren't compatible with event listeners

My HTML table structure varies depending on the content of the uploaded CSV file. I have integrated a plugin called Dragtable to make the table columns draggable. Additionally, I have implemented methods to add rows and columns. Here is an example of the a ...

What is the best way to add an image to a question or answer in a JavaScript quiz?

I'm in the process of designing a quiz that revolves around using images as questions or answer choices. For example, presenting an image of a cat and asking the user to select the corresponding 'cat' button. Unfortunately, my attempts to i ...

What is a reliable method to retrieve the text from the current LI if all LI elements in the list share the

I'm encountering an issue with retrieving the text from LI elements because I have 10 list items and they all have the same class name. When I attempt to fetch the text using the class name or id, I only get the text of the last item. Here is my code ...

Extract JSON data from a URL using the application/json protocol

I'm a beginner with PHP, Looking to retrieve parameters from the URL using an application/json request header. When checking the network in Chrome, it shows the Request URL as: test/rdp3.php/%5Bobject%20Object%5D In reality, it should be: test/rd ...

Display markers on the canvas

I am having trouble painting points from a JSON object on canvas using the following code. Can someone help me identify where I went wrong? var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); var t = [{"prevX":39,"prevY":58,"currX ...

Checkbox enabled Bootstrap image

I am encountering a minor issue where I am attempting to incorporate a simple image that can be toggled on and off by clicking on it. After coming across some bootstrap code online, I decided to test it in my project. Unfortunately, the code does not seem ...

The requested resource at http://js:port/socket.io/1/ could not be located (Error 404

Having trouble connecting with Socket.io. This is the server-side code: function chatserver(){ var express = require('express'), app = express(), server = require('http').createServer(app).listen(app.get('port'),function ...