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

Error: The method `push` within the `useHistory` function is causing an issue and is currently undefined

Whenever the home button is clicked, I need it to redirect to the homepage '/ '. However, I keep encountering this error. Any suggestions on what steps I should take to resolve this? : import { Route, useHistory } from 'react-router-dom/cjs/ ...

Tips for fading out two elements after completing a drag and drop action

Visit this Codepen for more examples - Codepen I have been developing a drag and drop feature in my application. Once the item is dropped, it transitions from red to green and fades out smoothly. The droppable element behind the draggable should also fad ...

Jquery animation is dragging its feet on Explorer, while other browsers are zipping along

Hey everyone, I am facing an issue with a simple jquery plugin I created for an animated menu. You can check out the entire site here: Main website My Library the "bootstrap" file The problem is that the red rectangle animates smoothly in Firefox, Op ...

Sending form data without interrupting the user interface by using asynchronous submission

Using jQuery version 1.7.2, I am currently using the submit() method to send a form via POST. This triggers a Python cgi-bin script that performs some tasks which may take around ten seconds to finish. Upon completion of the task, the Python script instruc ...

What is the best way to delete the onclick event of an anchor element?

Struggling to remove the onclick attribute using jQuery? Here's my code: function getBusinesses(page){ if(page==0){ alert("you are already on First Page"); $("#previous a").removeAttr("onclick ...

Obtain the identifier of a div within nested HTML components by utilizing jQuery

How do I retrieve the id of the first div with the class: post, which is "367", using jquery in the given HTML code: <div id="own-posts"> <span class="title">Me</span> <div class="posts_container"> <div class="post"& ...

Why does ng-bind fail to display values from rootScope that have been set by using ng-click?

I am trying to save a variable within $rootScope. When I have the following structure, everything works fine and the second div displays the value: <html ng-app> ... <body> <button ng-click="$rootScope.pr = !$rootScope.pr"></b ...

Ways to change the color of a TextView based on JSON data

I need assistance with setting the text color for a text view based on the JSON result provided below. When the statusspp is SPP, I want the text color to be red, and when the statusspp is SP2D, the text color should be green. Can you please help me achiev ...

Retrieve the data stored in a selection of checkbox fields on a form

I have a table of checkboxes: <div> <h1 class="text-center">Select activities</h1> <div class="row"> <div class="col"></div> <div class="col-md-8 col-lg-8"> <h3>Link activ ...

Leveraging multer for handling a FormData object in a node.js server

Having trouble with an HTML form that includes two buttons among other text input areas. The front-end javascript code is set up to handle the submit action by creating a FormData object to store the file and sending it via a jQuery AJAX request to a node. ...

Data is not being stored in Parse

I am currently facing a challenge while working with Parse for Javascript: When users sign up, along with their username and password, I also need to save their first and last names in Parse. However, at the moment, only the username and password are bein ...

creating a custom mongoose model using aggregation and filtering

My Review model includes two fields, product and rating. I want to calculate the total rating for a specific product and then find the average by dividing that total by 5. const mongoose = require('mongoose'); const ReviewSchema = mongoose.Sche ...

Disregard the sorting of rows in the MUI Datagrid

Any advice on excluding the "TOTAL" row from sorting in MUI library? onSortModelChange={(test, neww) => { neww.api.state.sorting.sortedRows = [14881337, 2, 3] neww.api.setState({...neww.api.state}) } } Review ...

Discover the method for generating five unique objects using data from ten records

I currently have 10 different entries stored in my database table. id value ------------ 1 record-1 2 record-2 3 record-3 4 record-4 5 record-5 6 record-6 7 record-7 8 record-8 9 record-9 10 record-10 M ...

Video player on website experiencing issues with playing VAST ads

Hey there! Check out this awesome site for Music Videos: (Music Videos(Player)) I've been testing different options, but if you have a better suggestion, please let me know. Any help would be really appreciated. If I can't figure it out on my o ...

Access previous value in Vuejs onchange event

In the code snippet below, how can I retrieve the previous value of the model that has been changed, specifically the age in vuejs? var app = new Vue({ el:"#table1", data:{ items:[{name:'long name One',age:21},{name:'long name Two&a ...

Dealing with Spring MVC: Error 415 when converting JSON to Pojo

While working on my jQuery code, I am creating JSON data and sending it to a controller using ajax. Here is the code snippet: var jsonResponse = []; $(columns).each(function() { if(!isEmpty($(this))) { var lang = $(this).find(".language"). ...

Trigger a popup notification with JavaScript when

Check out this snippet of code: <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/ ...

A method to find the sum of the final n elements in an array by employing Arr.reduceRight

I have successfully calculated the sum of the last n elements in an array using a for loop. Is it possible to achieve the same result using Arr.reduceRight instead? x = [1,2,3,4,5]; y = 0 for(let i=x.length; i>x.length-3; i--) { console.log(x[i-1]); ...