How to modify values in a JSON array using JavaScript

Currently, I am facing an issue with displaying dates properly on the x-axis of a graph created using Highcharts. To solve this problem, I need to parse the dates from the JSON response. Despite my attempts to manipulate the JSON date, I have not been able to achieve the desired outcome.

This is the current JSON response

"linechart":[{
                "name":"Average Conversation Length (In minutes)",
                "data":[["2020,02,12",12],["2020,02,13",13]]
            },{
                 "name":"Average Number of Conversations",
                 "data":[["2020,02,12",10],["2020,02,13",21]]
            }]

The expected output should be as follows:

linechart: [{name: "Average Conversation Length (In minutes)",
            data: [[Date.UTC(2020, 02, 12), 12],[Date.UTC(2020, 02, 13), 13]]},
            {name: "Average Number of Conversations",
            data: [[Date.UTC(2020, 02, 12), 10],[Date.UTC(2020, 02, 13), 21]]}],

Here is what I have tried so far:

    var arr1 = [];
var ​​data = chartdata.linechart
for (var i = 0; i < data.length; i++){
    var obj = data[i];
    for (var key in obj){
      var value = obj[key];
      for (var value2 in value){
        var values = value[value2];
        arr1.push(Date.parse(values));
      }
    }
  }

Answer №1

let visualData = chartdata.linechart;
for (let index = 0; index < visualData.length; index++) {
  let object = visualData[index];
  object.data.forEach(item => {
    item[0] = Date.parse(item[0]);
  });
}

console.log(visualData);

Answer №2

If you want to transform the elements, you can use the map method:

let barchart = [
  {
    "name":"Total Sales",
    "data":[["2021,01,25",5000],["2021,01,26",8000]]
},{
    "name":"Number of Orders",
    "data":[["2021,01,25",50],["2021,01,26",80]]
}]

const transformedData = barchart.map(item => {
    return {name: item.name, data: item.data.map( ([date, value]) => {
        return [new Date(date), value]
    })}
})

console.log(transformedData)

Answer №3

If you want to explore another method, consider the following:

const dataSet = [{
  "name": "Average Conversation Duration (In minutes)",
  "data": [
    ["2020,02,12", 12],
    ["2020,02,13", 13]
  ]
}, {
  "name": "Average Number of Interactions",
  "data": [
    ["2020,02,12", 10],
    ["2020,02,13", 21]
  ]
}];

dataSet.forEach(item => {
    item.data.forEach(data => {
        let date = data[0].split(',');
        
        data[0] = Date.UTC(date[0], date[1], date[2])
    })
})

https://jsfiddle.net/BlackLabel/ucx6ojL2/

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

"Create a dynamic entrance and exit effect with Tailwind CSS sliding in and out from

My goal is to create a smooth sliding animation for this div that displays details of a clicked project, transitioning in and out from the right side. This is my attempt using Tailwind CSS: {selectedProject !== null && ( <div classNam ...

Displaying a PHP variable on the console through the power of jQuery and AJAX

I'm attempting to display the value of a PHP variable in the browser's console using jQuery and AJAX. I believe that the $.ajax function is the key to achieving this. However, I am unsure about what to assign to the data parameter and what should ...

What is the best way to access a promise's value in global scope within a reactjs application?

Currently tackling user authentication using web tokens in react. My approach involves utilizing the fetch() method to send a POST request to my backend, facilitating CORS. The issue arises when attempting to employ the setToken() hook within the .then() b ...

Attach a click event listener to content loaded through AJAX using only JavaScript, without relying on jQuery

I'm curious about how to attach a click event to an element that will be added later through an ajax call. I know jQuery can handle this like so: $(document).on('click', '.ajax-loaded-element' function(){}); However, I'm not ...

Unending cycle occurs when utilizing a computed property alongside Vue Chart js

My goal is to refresh my chart with new data from an API call every 5 seconds. However, the chart is updating excessively, rendering each point hundreds of times. After checking the logs, I discovered that there seems to be an infinite loop causing this is ...

The administrator user assigns a user value in the authentication context, but that value remains hidden from the component where it was originally set

The authentication feature: import React, { useState } from 'react'; let selectedUserByAdmin = ''; const AuthContext = React.createContext({ setSelectedUserByAdmin: () => {}, selectedUserByAdmin, }); export const AuthContextPro ...

Having trouble displaying specific images on React Native, how can I resolve this issue?

I am currently developing a weather application that retrieves weather information and displays it using ForecastItem components. However, I have noticed that some of the components do not display the weather image randomly. On the Home screen, I use the ...

Transforming data from a singular object into an array containing multiple objects with key-value pairs

Looking for assistance with converting data from a single object in JSON format to another format. Here is the initial data: var originalData = { "1": "alpha", "2": "beta", "3": "ceta" } The desired format is as follows: var convertedData = ...

Creating a personalized aggregation function in a MySQL query

Presenting the data in tabular format: id | module_id | rating 1 | 421 | 3 2 | 421 | 5 3. | 5321 | 4 4 | 5321 | 5 5 | 5321 | 4 6 | 641 | 2 7 | ...

"Revamp your site with Vue and API for dynamic background

I'm faced with an issue where I am attempting to modify the background of a joke fetched from an API, but for some reason, the background is not changing and I can't seem to identify why. The main problem lies in my inability to change the proper ...

Utilize jQuery to swiftly align elements within a designated container

Check out my JSFiddle example: http://jsfiddle.net/c62rsff3/ I'm attempting to implement snapping behavior between 2 elements using this code: $('.draggable-elements').draggable({ snap: true }); In addition, I've defined a container ...

creating sleek animations with Pixi.js for circular shapes

Is it possible to create smooth animations on circles or sprites similar to D3.js hits in Leaflet? https://drive.google.com/file/d/10d5L_zR-MyQf1H9CLDg1wKcvnPQd5mvW/view?usp=sharing While D3 works well with circles, the browser freezes. I am new to Pixi. ...

appearing like a straightforward process of creating strings in JavaScript

Originally, I thought this task would be easy, but it ended up taking me the entire morning! var insert = '<div class="main_content_half_panel_circle" id="circle_' + c + '"></div><script type="text/javascript">$("#circle_& ...

Tally the quantity of data points within jQuery Datatables

Upon navigating to my jQuery DataTable, I aim to showcase the count of Users pending activation. Typically, I would use fnGetData with (this), but since I am not triggering this on a click event and wish to count all entries in the table, I am unsure of ho ...

Should I implement this practice when developing an AJAX website? Is it recommended to enable PHP code within .html files, or should I switch to using .php files instead?

Query: I am interested in executing PHP within HTML documents to include HTML using PHP include();. Question: Would it be more beneficial to change .php to .txt for my AJAX-loaded pages and switch my .html files to .php? This approach might resolve the ...

When a HTML table is generated from imported XML, DataTables will be applied

I am facing a challenge with my code and would appreciate some help. I am trying to load an XML file using jQuery and then use DataTables on my HTML table. However, the plugin doesn't seem to be functioning correctly. When I manually create an HTML ta ...

What led the Typescript Team to decide against making === the default option?

Given that Typescript is known for its type safety, it can seem odd that the == operator still exists. Is there a specific rationale behind this decision? ...

Initiate an AJAX request within an existing AJAX request

On one of my pages, page A, I have a form that passes parameters to a script using AJAX. The results are loaded into div B on the same page. This setup is functioning properly. Now, I want to add another form in div B that will pass parameters to a differe ...

Guide on determining if the value in a JSON object is a string or an array in Node.js

Running a Node.js application, I encountered the following JSON array structure. First JSON object: var json1= { bookmarkname: 'My Health Circles', bookmarkurl: 'http://localhost:3000/', bookmark_system_category: [ '22&apos ...

Display all items with pagination in a Material UI Table using React

I have recently implemented pagination in a react data table to handle a large number of entries. I wanted to add an option to display all entries by selecting "all" in the rowsPerPageOptions dropdown menu. Currently, I am able to show the count of all ent ...