working with received data from a JavaScript object

Looking for code assistance, I have a data object serving as my data source.

    var data = [   {
      "label":"May 7",
      "value":25736.6,
      "proID":"ISB"
   },
   // more data objects...
   ];

I'm manipulating this data to generate another object structure:

  const labelsAdded = new Set();
  // code logic...

My question is how can I dynamically place the extracted data in the correct date position?

  {
  "label":"May 8",
  "value":7893.3,
  "proID":"LI8"
  }

For example, if it's May 8 data, it should go under May 8 category. However, in my current implementation, it's not positioning properly causing graph inaccuracies due to incorrect placement.

Visit my jsfiddle link here for a clearer understanding of the issue described. See the problem image https://i.sstatic.net/sL3iz.png

Answer №1

 let propertyCount = Object.keys(data).length;
  let labelsSet = [...addedLabels];
  for(let j = 0; j < addedLabels.size; j++) {
     for(let y = 0; y < propertyCount; y++) {

        if(data[y].propertyID == 'ISB') {
            let index = Array.from(labelsSet).indexOf(data[y].label);
          propertiesObject.dataSource.dataset[0].data.push({value: null});
          propertiesObject.dataSource.dataset[0].data[index]=data[y];
        } 

        if(data[y].propertyID == 'LI8') {
          let index = Array.from(labelsSet).indexOf(data[y].label);
          propertiesObject.dataSource.dataset[1].data.push({value: null});
          propertiesObject.dataSource.dataset[1].data[index]=data[y];
        } 

        if(data[y].propertyID == 'DAC') {
          let index = Array.from(labelsSet).indexOf(data[y].label);
          propertiesObject.dataSource.dataset[2].data.push({value: null});
          propertiesObject.dataSource.dataset[2].data[index]=data[y];
        } 
     }
  }

In this code, I am adding data at matching label indices and filling in blank spaces with null values. Overall, the functionality works as expected. Great question!

LINK: http://jsfiddle.net/3ukj6L9q/45/

Answer №2

It seems that your code is aggregating all values for each date, which may not be the intended behavior.
Perhaps this revised version can address the issue:

var data = [{ label: "May 7",  value: 25736.6, proID: "ISB" }
          , { label: "May 8",  value: 7893.3,  proID: "LI8" }
          , { label: "May 8",  value: 30972.3, proID: "ISB" }
          , { label: "May 9",  value: 25060.7, proID: "ISB" }
          , { label: "May 9",  value: 17920.5, proID: "LI8" }
          , { label: "May 10", value: 16209.8, proID: "LI8" }
          , { label: "May 10", value: 62440.4, proID: "ISB" }
          , { label: "May 11", value: 14433.6, proID: "LI8" }
          , { label: "May 11", value: 48848.5, proID: "ISB" }
          ];

const Prop = { 'ISB': 0,  'LI8': 1,  'DAC': 1 }

const labelsAdded = new Set();

for (let {label} of data)
{
  if (labelsAdded.has(label)) continue 
  labelsAdded.add(label);
  propertiesObject.dataSource.categories[0].category.push({ label });
}

for (let xDate of labelsAdded) 
{
  for( let OnDate of data.filter(d=>d.label===xDate))
  {
    propertiesObject.dataSource.dataset[ Prop[OnDate.proID] ].data.push({value: OnDate.value});
  }
}

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 operation to remove the child element could not be completed

var first_content = document.getElementById('first-content'), offered_games = document.getElementById('offered-games'); for(var i = 0, e = offered_games.children; i < e.length; i++) { e[i].onmouseenter = function() { var ...

How can I utilize VeeValidate 3's locale message JSON files without the need for Node.js or an HTTP server?

With VeeValidate 2, the locale message files are in javascript format, making it possible to use them by including <script src='./vee-validate/dist/locale/ja.js'> without needing Node.js or an Http Server. However, with VeeValidate 3, the ...

Avoid refreshing the page upon pressing the back button in AngularJS

Currently, I am working on building a web application that heavily relies on AJAX with AngularJS. One issue I am facing is that when the user clicks the back button on their browser, the requests are being re-made which results in data having to be reloa ...

Removing an item from an array in Mongoose

I'm encountering an issue with removing an Object from an Array and I'm unsure of the correct way to use $pull for this action. Any help would be greatly appreciated! JSON data "accountId": "62efd8c008f424af397b415d", "l ...

Efficiently making JQuery Ajax requests using HTTP Basic Authentication

I am currently experiencing challenges with implementing HTTP Basic Authentication in JQuery when communicating with a REST-based server. This server provides responses in both XML and JSON formats, but I have chosen to work with JSON format. Our authoriz ...

What is the best way to showcase the outcome on the current page?

This is a sample HTML code for a registration form: <html> <head></head> <body> <form id="myform" action="formdata.php" method="post"> username:<input type="text" name="username" id="name"><br> password:&l ...

Change the format into a PHP array

In my workplace, I am confronted with a frustrating system that generates the following output: { party:"bases", number:"1", id:"xx_3039366", url:"systen01-ny.com", target:"_self", address:"Ch\u00e3o as Alminhas-Medas,Uteiros ...

Retrieve outcome from successful AJAX post and update HTML using globalEval

I have a function in JQuery that asynchronously posts data function post_data_async_globalEval(post_url, post_data, globaleval) { $.ajax({ type: 'POST', url: post_url, data: post_data, dataType: 'html', async: true, ...

Tips for utilizing a variable selector with jQuery's .attr() method

In a jQuery DataTable, there is a scenario where some values can be modified by clicking an edit button. When clicked, a modal popup appears with a form to enter new values for notes and status: ... "columnDefs": [ { ...

The download handler (php code) is being triggered multiple times within a single request

My PHP script is responsible for handling download requests. Clients can access this script using a GET request, as shown in the Javascript example below: if (true) { window.open('/download?mode=paper&fid=' + fid, '_blank'); re ...

Generate a CSV file using Javascript

I am working with an HTML table (table id='testTable') and a button in the HTML code: <button id="btnExport" onclick="javascript:xport.toCSV('testTable');">CSV</button> There is also JavaScript code involved: toCSV: func ...

Dynamically manipulate the perspective camera by moving and rotating it using a 4x4 matrix

Greetings, esteemed community members, For the past few days, I have been struggling with an issue related to updating the View Matrix (4x4) of my camera. This update is crucial for positioning objects within an AR-Scene created using three.js. The custo ...

Encountering an issue with Spring and AngularJS, as I am receiving an HTTP Status 404 error message

I'm encountering an HTTP Status 404 error within my controller. Server code @RequestMapping(value="/showMsg/", method=RequestMethod.GET,produces= { "application/json" })' public ResponseBody String show(){ HashMap hash = new HashMap(); ...

When working with a destination module, what is the best method for storing the value that is returned from an

I have a simple function that exports data passed into a function expression. In a separate node module, I am utilizing this imported function by passing in parameters. The function is being called within a router.post method as shown below: Below is the ...

"react commands" are not recognized as an internal or external command by any program or batch file

Initially, everything was working smoothly until I decided to download some updates from the git repository. However, upon execution, I encountered an error message stating that "react scripts" are not recognized as an internal or external command, operabl ...

When you reach the end of the page, the loadMore function is triggered multiple times

On my webpage, I have a list of profiles that are displayed. When the user reaches the bottom of the page, more data should be loaded through the loadMore function. While the loadMore function itself works correctly, I am facing an issue with the listener. ...

Tips for avoiding page reload when submitting a form with form.submit() in ReactJs

Is there a way to avoid the page from refreshing when triggering form submission programmatically in ReactJS? I have attempted to use this block of code: const myForm = () => <form onBlur={(e) => { if(!e.relatedTa ...

Refresh the view in AngularJS following a successful $http.get request

I have a <ul> in my HTML view that is populated based on a $http.get request. HTML: <div id="recentlyReleased" ng-controller="sampleRecordController as recCtrl"> <h1>Sample Records</h1> <ul> <li class= ...

Detecting duplicate key values within a JSON array using Angular.js

I am seeking a solution in Angular.js to verify if duplicate key values exist within a JSON array. Below is a breakdown of my code: var result=[{ "email":'<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec8dac8b ...

Visual traceroute, like the one on "yougetsignal.com", provides a way to update a div element either on demand or periodically

This is my very first question on a forum, yay! I will do my best to ask clearly and concisely. I am currently working on creating a visual traceroute similar to the one found on yougetsignal.com by Kirk Ouimet. My project is up and running using bash co ...