Ways to minimize the json data size

let c=[
      {
        "eventid": 29096475,
        "eventname": "Fortuna Dusseldorf v Stuttgart",
        "opendate": "2019-02-09T18:30:00.000Z",
        "eventtypeid": 1,
        "eventtypename": "Soccer",
        "marketname": "Match Odds",
        "marketid": "1.154041432",
        "runners": "[{\"selectionId\":879210,\"runnerName\":\"Fortuna Dusseldorf\",\"handicap\":0,\"sortPriority\":1},{\"selectionId\":44519,\"runnerName\":\"Stuttgart\",\"handicap\":0,\"sortPriority\":2},{\"selectionId\":58805,\"runnerName\":\"The Draw\",\"handicap\":0,\"sortPriority\":3}]",
        "totalmatched": "7.18",
        "selectionid": "879210",
        "backoddprice": "[{\"price\":2.12,\"size\":234.19},{\"price\":2.02,\"size\":272.12},{\"price\":1.94,\"size\":251.02}]",
        "layoddprice": "[{\"price\":2.36,\"size\":262.1},{\"price\":2.44,\"size\":15.95},{\"price\":2.58,\"size\":145.6}]"
      },
      {...}
    
      
    ]
    let ui=[]

    let j=c.reduce((o,a)=>{
     
     let inner=ui.filter(h=>h.eventid==a.eventid);
     if(inner.length>0)
      {
               a.runners.forEach(s=>{
      if(a.selectionid==s.selectionId)
      {
        let ones={};
        ones["selectionid"]=a.selectionid;
        ones["selectionname"]=s.runnerName;
        ones["backoddprice"]=a.backoddprice;
        ones["layoddprice"]=a.layoddprice;
        inner.runners.push(ones);


      }


    })


    console.log("llllllllllll");
      }

      else{
    let nn={};
    let inrunners=[];
    nn["eventid"]=a.eventid;
    nn["eventname"]=a.eventname;

    JSON.parse(a.runners).forEach(s=>{
      if(a.selectionid==s.selectionId)
      {
        let ones={};
        ones["selectionid"]=a.selectionid;
        ones["selectionname"]=s.runnerName;
        ones["backoddprice"]=a.backoddprice;
        ones["layoddprice"]=a.layoddprice;
        inrunners.push(ones);

      }


    })

    nn["runners"]=inrunners;
    o.push(nn);

      }
      
    return o;
      
    },[])

   console.log(JSON.stringify(j))

I have some data from the betfair api that requires sorting based on eventid and pushing runners array. I aim to achieve an output structure as specified below, where similar eventids are grouped together. Assistance in achieving this desired outcome would be greatly appreciated.

Expected format for each individual object

{
    "eventid": 29065439,
    "eventname": "Fortuna Dusseldorf v Stuttgart",
    "opendate": "2019-02-01T18:30:00.000Z",
    "eventtypeid": 1,
    "eventtypename": "Soccer",
    "marketname": "Match Odds",
    "marketid": "1.153118681",
  "runners": [
    {
      "selectionid": "879210",
      "selectionname": "Fortuna Dusseldorf",
      "backoddprice": "[{\"price\":2.12,\"size\":234.19},{\"price\":2.02,\"size\":272.12},{\"price\":1.94,\"size\":251.02}]",
      "layoddprice": "[{\"price\":2.36,\"size\":262.1},{\"price\":2.44,\"size\":15.95},{\"price\":2.58,\"size\":145.6}]"
    },
    {
      "selectionid": "44519",
      "selectionname": "Stuttgart",
      "backoddprice": "[{\"price\":3.3,\"size\":113.83},{\"price\":3.05,\"size\":180.24},{\"price\":2.9,\"size\":23.74}]",
      "layoddprice": "[{\"price\":3.95,\"size\":262.48},{\"price\":4.6,\"size\":84.74},{\"price\":1000,\"size\":4.48}]"
    },
    {
      "selectionid": "58805",
      "selectionname": "The Draw",
      "backoddprice": "[{\"price\":3.25,\"size\":116.58},{\"price\":3.05,\"size\":224.71},{\"price\":1.01,\"size\":139.27}]",
      "layoddprice": "[{\"price\":3.95,\"size\":139.17},{\"price\":4.3,\"size\":122.84},{\"price\":4.5,\"size\":86.06}]"
    }
  ]
}

My current attempts to solve this challenge has been constrained due to the size of the provided data. Any assistance in resolving this issue would be highly valued.

Answer №1

I couldn't make a connection between the input JSON and the expected output JSON.

For testing, you can use this JSFiddle link: https://jsfiddle.net/4tv0dsw6/

let data=[
      {
        "eventid": 29096475,
        "eventname": "Fortuna Dusseldorf v Stuttgart",
        "opendate": "2019-02-09T18:30:00.000Z",
        "eventtypeid": 1,
        ...
      
      },
      
      ...
    ];
 console.log("data", data)

//The code starts here
    result = [];
    mappedEventIds = [];
    a = data.reduce((v, k)=>{
    k.runners = JSON.parse(k.runners);    
    k.backoddprice = JSON.parse(k.backoddprice);
    k.layoddprice = JSON.parse(k.layoddprice);

    eventIndex = mappedEventIds.indexOf(k.eventid);
     if(eventIndex === -1){
     //if not already mapped
     mappedEventIds.push(k.eventid);
     for(var i =0; i < k.runners.length; i++){
      k.runners[i].backoddprice = k.backoddprice;       

      k.runners[i].layoddprice = k.layoddprice;
     }
     result.push(k);
     }else{
      //if mapped already
      // I think this is duplicated, if yes. comment out or delete this else loop
      for(var i =0; i < k.runners.length; i++){
                k.runners[i].backoddprice = k.backoddprice;                  
                 k.runners[i].layoddprice = k.layoddprice;
            result[eventIndex].runners.push(k.runners[i]); 
      }

     }

  });
  console.log("result", result);

Answer №2

Introducing a new approach using an Event class that generates a keyRunner(). The keyRunner is pulled from the array of runners based on the matching id within the outer object. This method, while not fully comprehended in terms of semantics, adds the backoddprice and layoddprice to the final object for the desired output.

(removed mention about mergedRunners vs runners arrays)

I hope this meets your requirements. If not, I believe it highlights the importance of abstraction and thoughtful variable naming when resolving such challenges.

let c = [{
    "eventid": 29096475,
    "eventname": "Fortuna Dusseldorf v Stuttgart",
    "opendate": "2019-02-09T18:30:00.000Z",
    "eventtypeid": 1,
    ...
console.log(mergedEvents.map(me => me.asPrintable()));

Answer №3

Perhaps not the most optimal solution, but based on your description, here is a potential approach to consider:

let c=[
      {
        "eventid": 29096475,
        "eventname": "Fortuna Dusseldorf v Stuttgart",
        "opendate": "2019-02-09T18:30:00.000Z",
        "eventtypeid": 1,
        "eventtypename": "Soccer",
        "marketname": "Match Odds",
        "marketid": "1.154041432",
        "runners": "[{\"selectionId\":879210,\"runnerName\":\"Fortuna Dusseldorf\",\"handicap\":0,\"sortPriority\":1},{\"selectionId\":44519,\"runnerName\":\"Stuttgart\",\"handicap\":0,\"sortPriority\":2},{\"selectionId\":58805,\"runnerName\":\"The Draw\",\"handicap\":0,\"sortPriority\":3}]",
        "totalmatched": "7.18",
        "selectionid": "879210",
        "backoddprice": "[{\"price\":2.12,\"size\":234.19},{\"price\":2.02,\"size\":272.12},{\"price\":1.94,\"size\":251.02}]",
        "layoddprice": "[{\"price\":2.36,\"size\":262.1},{\"price\":2.44,\"size\":15.95},{\"price\":2.58,\"size\":145.6}]"
      }, ...

// The rest of the data and code has been kept unchanged for further processing

console.log(JSON.stringify(newJson, null, 4))

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

The mongoose.populate() method is failing to display the populated content

// defining user schema const mongoose = require('mongoose'); const {ChatRoom} = require('./chatRoom'); const userSchema = new mongoose.Schema({ _id: mongoose.Schema.Types.ObjectId, username:{ type: 'String', unique ...

Ajax is transmitting the data, however, PHP is unable to receive it

I am utilizing the power of ajax to transmit data to a php function. My ultimate goal is to exhibit rows of data based on the variable $tweetdate. Below is the snippet of my ajax script: jQuery('#bootstrapModalFullCalendar').fullCalendar({ d ...

The issue of Vuetify table failing to scroll in IE11

Having trouble getting Vuetify to function in my Vue project on IE11. I need to make content responsive when it's not available, or add a horizontal scroll bar in IE11 when the content is too wide. [Visit this Codepen for reference][1] [1]: https ...

`Troubleshooting Json parsing issues on Android platform`

An issue has arisen while attempting to parse a JSON array in my Android application. The JSON object is structured as follows: {"post":[ [{"0":"all the best to every one...!!","post":"all the best to every one...!!"}, {"0":"hello every one... ...

Advanced jq Filtering Techniques

Just to clarify, this is not an academic assignment; it's a modified version of a task I'm handling at work. I'm currently using jq to filter JSON data and aiming to produce an object for each matching record in my filter. The task at hand ...

What is the issue with this asynchronous function?

async getListOfFiles(){ if(this.service.wd == '') { await getBasic((this.service.wd)); } else { await getBasic(('/'+this.service.wd)); } this.files = await JSON.parse(localStorage.getItem('FILENAMES')); var ...

Effective strategies for integrating Bootstrap and AngularJS without relying on jQuery

Currently exploring AngularJS after experimenting with Twitter's Bootstrap. I appreciate Bootstrap for its simplicity, sleek design, and mobile-friendliness. On the other hand, I have noticed a trend where people recommend using AngularJS over jQuery, ...

Android app encountering Volley throwing JsonPars exception

Hey there! I am a beginner in Android development and I'm trying to get some practice with Volley. Below is a code sample that I wrote: RequestQueue rq = Volley.newRequestQueue(this); String urlStr="https://api.github.com/users/mralexgray/repos"; ...

Display requested tab feature using jQuery upon page load

I am new to jquery and have been using this code for creating tabs: <script type="text/javascript" charset="utf-8> $(function () { var tabContainers = $('div.tabs > div'); tabContainers.hide().filter(':first&apo ...

What is the best way to allow my limit to be as greedy as possible?

I'm facing an issue with the code below where it currently only matches MN. How can I modify it to also match KDMN? var str = ' New York Stock Exchange (NYSE) under the symbol "KDMN."'; var patt = new RegExp("symbol.+([ ...

The left margin in Carousel is malfunctioning when it comes to hovering

I would like to achieve an effect where, on hover, my images shift the other images to both the left and right. However, currently when hovered, all the images shift to the right only. The code snippet in question is as follows: .item-img:hover { trans ...

Automatically activate the next tab in Bootstrap

I have a modal that performs a count. Once the count is completed, the modal closes. My goal is to automatically switch to the next tab in Bootstrap when the modal closes. Here is the HTML: <ul class="nav nav-tabs namelocationtable"> <div clas ...

The process of reversing an array is not fully completing due to the pop method being used within a loop

Note: I've been immersed in code for hours now and have reached a stage where I'm starting to doubt the spelling of every word or question if I have dyslexia. Despite this, I know this should be a simple question. I want to create a basic functi ...

Checking if a module is loaded through dynamic route code splitting

One issue with code splitting is that when the module is large, the initial loading time may result in a blank screen and delay for the user. function errorLoading(err) { console.error('Dynamic page loading failed', err); } fu ...

In Javascript, you can quickly update other variables with just a one-line conditional statement

Is there a way to simplify this code into one line without using an if-else statement? For example, updating all variables when a specific condition is met? const dogStatus = present ? "bark" : "beep"; const catStatus = present ? "meow" : "meep"; const f ...

Transforming an ES6 JSON object into a dictionary: a step-by-step guide

As someone who is new to learning ES6 and JQuery, please forgive me if this question has been asked before (I couldn't find similar ones). Currently, I am working on retrieving data from a JSON file in the following format: { EUR: { code: "EUR" ...

What is the best way to add content to the ajax success code?

For my project, I have a lot of content in the success function of AJAX. I plan to move this content to a file called textcsc.js and use the include() method in AJAX. Initially, the code was working successfully: $(document).ready(function() { $(&apo ...

What makes React stand out as a server side rendering technology when compared to Angular?

While delving into the world of ReactJs, I discovered a unique comparison between its rendering aspect and AngularJs. Interestingly, some refer to ReactJs as a server-side rendering technology. This revelation has truly caught me off guard! To explore fu ...

Swapping React components within a list: How to easily change classes

For my latest project, I am building a straightforward ecommerce website. One of the key features on the product page is the ability for users to select different attributes such as sizes and colors. These options are represented by clickable divs that pul ...

NodeJS authentication using Express-Session and Passport encounters errors

I have successfully implemented authentication and login functionality using the Google OAuth API in my NodeJS backend. const passport = require('passport'); const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; ...