Generating various arrays of data

I am currently facing an issue with creating separate datasets based on the month value. Despite my efforts, all month values are being combined into a single dataset in my code.

Any assistance in dynamically generating different datasets would be greatly appreciated. I have included a link to the fiddle where I attempted to use my data object:

JSFIDDLE

var obj = [{
    date: "2017-06-01",
    reqC: "129963",
    month: "JUNE",
    resC: "80522"
  }, {
    date: "2017-06-05",
    reqC: "261162",
    month: "JUNE",
    resC: "83743"
  },{
    date: "2017-07-03",
    reqC: "438860",
    month: "JULY",
    resC: "166107"
  }]
  var maindataset = [];
  var dataset = [];
 ["reqC", "resC"].forEach((series) => {
    dataset.push({
      seriesname: series,
      data: obj.map((el) => {
        return el[series]
      })
    })

  });
  maindataset.push({
    dataset: dataset
  });
  alert(JSON.stringify(maindataset));

// Expected Output  

{
  "dataset": [
    {
      "dataset": [                 //June
        {
          "seriesname": "Req",   
          "data": [
            {
              "value": "129963"
            },
            {
              "value": "261162"
            }
          ]
        },
        {
          "seriesname": "Res",
          "data": [
            {
              "value": "80522"
            },
            {
              "value": "83743"
            }
          ]
        }
      ]
    },
    {
      "dataset": [                   //July
        {
          "seriesname": "Req",
          "data": [
            {
              "value": "438860"
            }
          ]
        },
        {
          "seriesname": "Res",
          "data": [
            {
              "value": "166107"
            }
          ]
        }
      ]
    }
  ]
}

Answer №1

One potential solution involves using a nested hash table and then iterating through the keys to extract the desired information.

var data = [{ date: "2017-06-01", reqC: "129963", month: "JUNE", resC: "80522" }, { date: "2017-06-05", reqC: "261162", month: "JUNE", resC: "83743" }, { date: "2017-07-03", reqC: "438860", month: "JULY", resC: "166107" }],
    result = { dataset: [] },
    parts = { reqC: 'Req', resC: 'Res' },
    hash = { _: result.dataset };

data.forEach(function (a) {
    var temp = hash;
    if (!temp[a.month]) {
        temp[a.month] = { _: [] };
        temp._.push({ dataset: temp[a.month]._ });
    }
    temp = temp[a.month];
    Object.keys(parts).forEach(function (k) {
        if (!temp[k]) {
            temp[k] = { _: [] };
            temp._.push({ seriesname: parts[k], data: temp[k]._ });
        }
        temp[k]._.push({ value: a[k] });
    });
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To organize your data effectively, you can group it by month and then structure the output accordingly. Take a look at the code snippet below.

var obj = [{
    date: "2017-06-01",
    reqC: "129963",
    month: "JUNE",
    resC: "80522"
  }, {
    date: "2017-06-05",
    reqC: "261162",
    month: "JUNE",
    resC: "83743"
  },{
    date: "2017-07-03",
    reqC: "438860",
    month: "JULY",
    resC: "166107"
  }];

var result = {};

var groups = obj.reduce(function(acc, obj) {
  acc[obj.month] = acc[obj.month] || [];
  acc[obj.month].push(obj);
  return acc;
}, {});

//console.log(groups);

result.dataset = Object.keys(groups).map(function(key) {
  return {
    dataset: [{
      "seriesname" : "Req",   
      "data": groups[key].map(function(o) {
        return { value : o.reqC };
      })
    }, {
      "seriesname" : "Res",   
      "data": groups[key].map(function(o) {
        return { value : o.resC };
      })
    }]
  };
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

Avoid using the same property name for an object more than once. There is a data object in your code snippet that appears like this:

"data": [
      {
        "value": "80522"
      },
      {
        "value": "83743"
      }
    ]

To resolve this issue, you can either modify the keys to be unique like so:

"data": [
      {
        "value1": "80522"
      },
      {
        "value2": "83743"
      }
    ]

Alternatively, you can convert it into an array format:

"data": [ "80522", "83743" ]

Answer №4

Make sure to include the month in your validation process. Give this code a shot:

    var obj = [{
    date: "2017-06-01",
    reqC: "129963",
    month: "JUNE",
    resC: "80522"
  }, {
    date: "2017-06-05",
    reqC: "261162",
    month: "JUNE",
    resC: "83743"
  },{
    date: "2017-07-03",
    reqC: "438860",
    month: "JULY",
    resC: "166107"
  }]
  var maindataset = [];

  ["JUNE","JULY"].forEach((month)=>{
  var dataset = [];
     ["reqC", "resC"].forEach((series) => {
      dataset.push({
        seriesname: series,
        data: obj.reduce((filtered, el) => {
          if(el["month"] === month){
           filtered.push({value: el[series]});
           }
           return filtered;
        },[])
      })

    });
    maindataset.push({
      dataset: dataset
    });
  })

  alert(JSON.stringify(maindataset));

Here is the expected output:

[{
    "dataset": [{
        "seriesname": "reqC",
        "data": [{
            "value": "129963"
        }, {
            "value": "261162"
        }]
    }, {
        "seriesname": "resC",
        "data": [{
            "value": "80522"
        }, {
            "value": "83743"
        }]
    }]
}, {
    "dataset": [{
        "seriesname": "reqC",
        "data": [{
            "value": "438860"
        }]
    }, {
        "seriesname": "resC",
        "data": [{
            "value": "166107"
        }]
    }]
}]

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

Ensure that the modal remains open in the event of a triggered keydown action, preventing it from automatically closing

I am currently toggling the visibility of some modals by adjusting their CSS properties. I would like them to remain displayed until there is no user interaction for a period of 3 seconds. Is there a way to achieve this using JavaScript? Preferably with Vu ...

Distinguishing between selecting rows and selecting checkboxes in Mui Data Grid

Is there a way to differentiate between clicking on a row and clicking on the checkboxes? I want to be able to select multiple rows by clicking anywhere in the row except for the checkbox column. When clicking outside the checkbox column, I would like to p ...

Is there a way to separate a string using two different delimiters?

Here is my code snippet : <template> ... <p v-for="club in clubs">{{club}}</p> ... </template> <script> export default { data: () => ({ clubs: '' }), mounted () { let dataClub = "- ...

Customized function enabling dynamic menu display based on varying screen dimensions

Looking for assistance with JS and jQuery as I am relatively new to it. Any help would be greatly appreciated... I'm currently working on a responsive header where I want to implement onclick functions for mobile and tablet resolutions only. I' ...

"Efficiently Browsing Through Various Links with the Help of Greasemon

My goal is to open approximately 25 hyperlinks from a single page. All of these hyperlinks include the text Free Win. I am looking for a solution that will open each individual link in a new tab within the browser. I have written a Greasemonkey script, ...

The dropdown menu vanishes from sight as soon as the cursor moves away from a link

Recently, I encountered an issue while trying to create a dropdown menu using Jquery. The problem arose when attempting to select the second link, as the entire menu would disappear. Additionally, is there a way to ensure that only one dropdown menu is vis ...

Issues with CreateJS chained animations failing to reach their intended target positions

Currently, I am tackling a project that involves using Three.js and CreateJS. However, I have encountered an issue with the animations when trying to move the same object multiple times. The initial animation fails to reach the target position, causing sub ...

Ways to retrieve nested data from an object

I have added an object with categories in a database. It displays the price and date of addition. How can I output the date to the console? Currently, in the console, it shows: [ [ { cost: '50$', date: [Object] } ] ]. I need to extract the inform ...

What is the method for integrating JSON into the gdata objective-c framework?

After following the instructions provided in this guide to integrate the framework: However, during the compilation process, I encountered the following error: Error: /devfolder/gdata-objectivec-client-read-only/Source/JSON/SBJsonBase.h: No such file or ...

How to properly handle sending an empty post request in Angular 2

My current issue revolves around attempting to send data from my application to the server using a POST request, however, the server seems to be receiving empty POST data. This is the function responsible for sending the data: private headers = new Heade ...

Tips for creating a tooltip above an SVG circle with AngularJS

I'm currently working on a project where I am using AngularJS and SVG to plot circles on a page. My goal is to have a tooltip appear when a user hovers over one of the circles. I came across an explanation on how to achieve this on this website, but u ...

Exploring AngularJS JSON Parsing Techniques (such as utilizing ng-repeat)

My approach to processing json data looks like this: $scope.activities = response.data; console.log($scope.activities.length); var list = []; for (var i = 0; i < $scope.activities.length; i++) { console.log($scope.activities[i].name); list.pus ...

Arranging xCharts based on the weekday order

Struggling with xCharts, specifically trying to display a bar chart showing numbers with corresponding days of the week in order. Despite my efforts, I can't seem to get them to appear in the correct sequence. Refer to the image below for reference: ...

Tips for modifying style.display using JavaScript

On my website, the menu is structured like this: <nav id="menu"> <label for="tm" id="toggle-menu">Menu <span class="drop-icon">▾</span></label> <input type="checkbo ...

What is the process for eliminating a field from an Angular Reactive Form?

I am working with an Angular form that needs to be sent to the API and it includes 4 fields: username, email, password, and confirmpassword. However, I only want to send three of them - username, email, and password. Does anyone have any suggestions on ho ...

Extract data from CSV files with line breaks in fields using JavaScript

When dealing with a CSV file that has newline or return characters in certain fields, the challenge is to parse the data without accidentally splitting a field into multiple rows. Here is an example of CSV data: ID;Name;Country;ISO-2;Address;Latitude;Lon ...

Different choices for data attributes in React

Recently, I downloaded a new app that requires multiple API calls. The first API call retrieves 20 Objects, each with its own unique ID. The second API call is made based on the IDs from the first call. To display this data in my component: <div> ...

Sharing and showcasing files directly from a local directory

Recently diving into NodeJS and web development, I've successfully used multer to upload a single file within my web application. The file gets uploaded to my "uploads" folder flawlessly, and now I'm planning on storing the file path in my databa ...

How can I effectively display a blank menu item for the SelectField component in Material-UI within a React application?

I am using the select-field component from the material-ui framework version 0.15.4 with React version 15.4.0. I am attempting to add a blank menu-item to the select-field in order to allow for deselecting a value in the dropdown field when clicked. Howeve ...

Quantifying the passage of time for data entry

Looking to create a quiz form where I can track how long it takes users to input/select answers. I attempted the following code but the timing seems off: $('input, select').on('focus', function(event) { el = $(this); name ...