Using JavaScript to organize and reformat JSON data into grouped structures

In my dataset, I am unable to make any formatting adjustments or modifications.

//input json data
[
    {
        "Breaks":[
                {"points":12,"points_total":12,"average":8.0,"faults":[]},
                {"points":17,"points_total":29,"average":11.6,"faults":[]},
                {"points":6,"points_total":35,"average":11.6667,"faults":[]},
                {"points":8,"points_total":43,"average":10.75,"faults":[]},
                {"points":14,"points_total":57,"average":11.4,"faults":[]},                 
            ],
        "team_name":"King Sports"
    },

    {
        "Breaks":[
            {"points":18,"points_total":18,"average":15.4286,"faults":[]},      
            {"points":2,"points_total":20,"average":10.0,"faults":[]},
            {"points":7,"points_total":27,"average":9.0,"faults":[]},
            {"points":9,"points_total":36,"average":9.0,"faults":[]},
            {"points":4,"points_total":40,"average":8.0,"faults":[]},
            {"points":4,"points_total":44,"average":7.33333,"faults":[]},
            {"points":4,"points_total":48,"average":6.85714,"faults":[]},
            {"points":8,"points_total":56,"average":7.0,"faults":[]},
            {"points":1,"points_total":57,"average":6.33333,"faults":[]},
            {"points":6,"points_total":63,"average":6.3,"faults":[]},
            {"points":3,"points_total":66,"average":5.82353,"faults":[]},
            {"points":6,"points_total":72,"average":6.0,"faults":[]},
            {"points":7,"points_total":79,"average":6.07692,"faults":[]},
            {"points":3,"points_total":82,"average":5.85714,"faults":[]},
            {"points":0,"points_total":82,"average":5.65517,"faults":[]}
        ],
    "team_name":"Lion Sports"
    }
]

My goal is to restructure the data to achieve the following results. In the output, there should be 20 "Breaks", and if no value is found in "Breaks" it should be represented as "null".


//the result what i wanted = output expected

 [
     ['Breaks', 'King Sports', 'Lion Sports'],
     ['1',  12, 18],
     ['2',  29, 20],
     ['3',  35, 27],
     ['4',  43, 36],
     ['5',  57, 40],
     ['6',  null, 44],
     ['7',  null, 48],
     ['8',  null, 56],
     ['9',  null, 57],
     ['10',  null, 63],
     ['11',  null, 66],
     ['12', null, 72],
     ['13',  null, 79],
     ['14',  null, 82],
     ['15',  null, null],
     ['16',  null, null],
     ['17',  null, null],
     ['18',  null, null],   
     ['19',  null, null],
     ['20',  null, null]
 ]  

Answer №1

Start by creating the result array and then insert the values.

var data = [{ Breaks: [{ points: 12, points_total: 12, average: 8.0, faults: [] }, { points: 17, points_total: 29, average: 11.6, faults: [] }, { points: 6, points_total: 35, average: 11.6667, faults: [] }, { points: 8, points_total: 43, average: 10.75, faults: [] }, { points: 14, points_total: 57, average: 11.4, faults: [] }], team_name: "King Sports" }, { Breaks: [{ points: 18, points_total: 18, average: 15.4286, faults: [] }, { points: 2, points_total: 20, average: 10.0, faults: [] }, { points: 7, points_total: 27, average: 9.0, faults: [] }, { points: 9, points_total: 36, average: 9.0, faults: [] }, { points: 4, points_total: 40, average: 8.0, faults: [] }, { points: 4, points_total: 44, average: 7.33333, faults: [] }, { points: 4, points_total: 48, average: 6.85714, faults: [] }, { points: 8, points_total: 56, average: 7.0, faults: [] }, { points: 1, points_total: 57, average: 6.33333, faults: [] }, { points: 6, points_total: 63, average: 6.3, faults: [] }, { points: 3, points_total: 66, average: 5.82353, faults: [] }, { points: 6, points_total: 72, average: 6.0, faults: [] }, { points: 7, points_total: 79, average: 6.07692, faults: [] }, { points: 3, points_total: 82, average: 5.85714, faults: [] }, { points: 0, points_total: 82, average: 5.65517, faults: [] }], team_name: "Lion Sports" }],
    result = data.reduce(function (r, a, i) {
        r[0][i + 1] = a.team_name;
        a.Breaks.forEach(function (b, j) {
            r[j + 1][i + 1] = b.points_total;
        });
        return r;
    }, function (length) {
        var a = Array.apply(null, { length: length + 1 }).map(function (_, i) { return [(i || 'Breaks').toString(), null, null] });
        return a;
    }(20));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Disparity in React app: Misalignment between debugger and console output

Throughout the years, I've encountered this issue in various ways, and I have finally been able to articulate it. Take a look at the code snippet below: import React, {Component} from "react"; import aFunction from "./Function"; export default class ...

Issue with Colorbox plugin preventing ASP.NET button from triggering postback

Currently utilizing the colorbox modal plugin (http://colorpowered.com/colorbox/) I'm facing an issue with a simple form placed in a master page - the submit button is unresponsive and doesn't trigger any action. It seems like several users are ...

Have Babel transpile configuration files into CommonJS format

I'm having trouble getting my Nuxt app to work with Jest for testing. I have a setupFilesAfterEnv property set with a setupTests.ts file that imports a translation file. The translations file uses ES6 import/export module syntax, but it seems like my ...

Tips for extracting parameters from a JSON String using JavaScript

When attempting to parse a JSON String, I am encountering an issue where the parsed value is coming up as undefined. You can view the code on this jsfiddle link. <input type="submit" onclick=testJSON() value="Test"/> <div i ...

Iterate through JSON data and access values based on keys using a $.each loop

I have retrieved JSON data from the controller using AJAX and now I want to access this data. The data is in the form of a list of objects (array) with key-value pairs, so I am planning to use .each() function to go through all the data. The array looks li ...

Issue with Build System CTA's/Callback function functionality not operational

I have encountered an issue with my build/design system. Although everything works fine during development, when I publish my package and try to use the callback function, it does not return the necessary data for me to proceed to the next screen. I tried ...

Parse JSON array into Go struct when the array is embedded within the JSON string

I’m a beginner in Go and currently working with a weather API. I have encountered an issue with unmarshalling the JSON data. The problem seems to be related to having an array within the JSON string structure, which is causing difficulties in defining ...

What is the process for obtaining the number of video views using the YouTube API?

I have a straightforward question: How can I retrieve the number of video views using the YouTube API? Although the task is simple, I need to perform this query on a large number of videos frequently. Is there a way to access their YouTube API in order to ...

The error message "mapboxgl is not defined" indicates that the mapboxgl variable

I have been encountering the following error message in the console, and despite spending hours trying to troubleshoot it, I have been unsuccessful in resolving the issue. Could someone assist me in fixing this problem? error image I am having difficulty ...

A step-by-step guide on changing the class of a focused contenteditable element with a button click using jQuery

I need assistance changing the class of an element within a contenteditable div. Here is my current code: <button>swap class</button> <div contenteditable="true"> <h1 class="line-height-1">Your Headline Here</h1> </di ...

Navigating through two nested arrays in JavaScript to access an object

Having difficulty extracting the nested car values using JavaScript (lodash). Take a look at the JSON data below: { "cars":[ { "nestedCars":[ { "car":"Truck", "color" ...

Finding elements based on a specific parent structure in JavaScript: A step-by-step guide

I'm currently working on a script that needs to grab content only within a specific parent structure defined as div.main-element input+label+ul. Is there a way to achieve this using JavaScript or jQuery? If anyone could point me in the right directi ...

How can I merge an array of objects in lodash?

I am facing a challenge with merging an array of objects in JavaScript. My goal is to combine them into a single object using either a JS library or lodash. Here is how my array looks: [{ 2017: { a: "100", b: "200" ...

Invoking functions from controllers to mongoose schema module in Node.js

Greetings everyone, I am fairly new to working with Node.js so let me share my current dilemma. I have set up a mongoose schema for handling comments in the following structure: const mongoose = require("mongoose"); const Schema = mongoose.Schema; const ...

Changing state property upon clicking child element in React is not feasible

I am interested in changing the text color upon clicking it using a function triggered in a child element that affects the parent's state. This is because a specific property of the parent determines whether the text should be one color or another. W ...

Modifying data on the fly for a Highcharts series

My chart is currently functioning well with data in the options. However, when I leave the data empty for a series and attempt the following code (in order to change the data based on a click event), it fails to work. Any suggestions on how I can rectify ...

Understanding the difference between NULL and the absence of a value is crucial when working with JSON Merge Patch in NetCore WebApi and System.Text

I am looking to implement support for partial updates using JSON Merge Patch. The current domain model follows the always valid concept and does not have any public setters. This makes it challenging to directly apply changes to the class types. As a resul ...

"Encountering an issue with Express.json where it fails to parse the

Receiving JSON POST data from an IoT API that includes multipart form-data. Occasionally, an image file may be included but I only want to focus on the JSON part: POST { host: '192.168.78.243:3000', accept: '*/*', 'content-le ...

Error: The TVJS Framework encountered a JSON Parse issue due to an unexpected EOF

I am currently developing a TVML application specifically for Apple TV. However, when I attempt to execute this code to send a request to a remote server, I encounter the following error: SyntaxError: JSON Parse error: Unexpected EOF. My goal is to run thi ...

Channeling requests from webpack dev server to .net MVC website

I am working on incorporating Vue into my .net MVC project. After installing Vue using the CLI, I included the following vue.config.js: module.exports = { devServer: { proxy: { '/': { target: 'http://mvcsite.local', ...