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

Incorporating Json.Net into a Unity3D game development venture

After adding the Json.Net library to Visual Studio 2013 using NuGetpackage and installing it for NetFramework 4.5, everything seemed fine in Visual Studio with no errors when adding using Newtonsoft.Json; However, when working with Unity3D 5.0, an error ...

I am struggling to get the pop-up to close using the current code. I suspect that the issue might be related to the variable I was previously using in WordPress. I have made changes but the pop-up

While delving deeper into the realm of Javascript, I encountered a stumbling block with a single popup intended for the main page of a WordPress website I am constructing. Despite my attempts to modify the code's variables, they seem unyielding. Surpr ...

Designing a login system with MEAN stack architecture?

I am currently in the process of building a web application using the MEAN stack (MongoDB, Express, AngularJS, and node.js). Specifically, I am working on implementing a login system and securing certain routes in my Angular app so that they are only acces ...

How to display an array with JSON objects in Angular 4

Looking to display specific data from an array in my .html file that originates from my .ts file: myArray: ["03/05/2018", "2:54", "xoxo", "briefing", "your", [{ "Id": "1", "Time": "20:54", "Topic": "mmmmm", "GUEST1": { "Role": "HS" ...

Modifying a variable within the return statement in a React Native component

I am relatively new to React and React-native and I am facing challenges in understanding how to update a variable within the return method. Here is my current code snippet: import React, { Component } from "react"; import { View, StyleSheet, Platform, T ...

The ES6 reduce method is not giving the expected result

In Image 1, the output you will see if you log the final array from Snippet 1. My goal is to transform my array to match the format shown in Image 2. I attempted using lodash's _.uniqBy() method [Snippet 2], but the logged output of the reduce varia ...

Strategies for consistently receiving updates of Iframe content body within a react useEffect hook

When loading html into an iframe using srcDoc with the sandbox="allow-same-origin", I face a challenge. Despite the content displaying properly, the property frameRef.contentDocument.body.innerHTML remains empty. This issue persists even after s ...

What is the procedure for passing arguments using slurpfile and jq?

I'm attempting to transform this query: cat input_file.json | jq '.arrlstProperty[] | select(.code == "123" or .code=="345" or .code="678")' > output.json Into this: cat input_file.json | jq '.arrlstPro ...

The function of style.marginRight differs from that of style.marginLeft

One function aligns content to the left while the other doesn't align it to the right function openNavLeft() { document.getElementById("mySidenavLeft").style.width = "100vw"; document.getElementById("main").style.marginLeft = "100vw"; } function ...

Extra assistance might be required to manage the output from these loaders

I'm in the process of developing a State Management Library for ReactJs. However, when I integrate it into my React project (built with create-react-app), an error is thrown: Failed to compile. path/to/agile/dist/runtime.js 116:104 Module parse faile ...

Sending an event to a component that has been rendered in Vue

I'm currently in the process of developing a custom rendered component that will execute a function when clicked on: // Creating a standard Vue component with a render function Vue.component('greeting', { methods: { sayHello(){ ...

The HttpRequest.getString function is encountering an error even though it is functioning properly

Seeking assistance from the community here! I have implemented a service in Polymer Dart to load a Json feed with this code: Future loadService(){ return HttpRequest.getString(_serviceURL) .then(buildView) .catchError(handleError); } Althoug ...

abandoning the upload of an item into a THREE.js environment

Currently, I am working on a THREE.js scene where I need to prevent uploading multiple files into the scene simultaneously. The setup involves using Angular to implement the three js scene and canvas as a factory to maintain only one instance of a canvas a ...

Attempting to provide varying values causes If/Else to become unresponsive

I've implemented a function that scans a file for a specific term and then outputs the entire line as a JSON object. Strangely, when I include an else statement in the logic, an error occurs: _http_outgoing.js:335 throw new Error('Can\& ...

How can we access a value within a deeply nested JSON object in Node.js when the key values in between are not

In the nested configuration object provided below, I am seeking to retrieve the value associated with key1, which in this case is "value1". It's important to note that while key1 remains static, the values for randomGeneratedNumber and randomGenerated ...

Quick way to specify type for Observable in Typescript

Exploring Shortcut Declarations When working with TypeScript, I often take a shortcut when declaring object shapes. Instead of creating an interface first and then specifying that the object conforms to that type, I simply do: object: { fizz: boolean, buz ...

What is the best way to retrieve the [id]/routeName in Next.js?

I'm working on a straightforward project where users visit links like: localhost:3000/course/[id]. Once they click join, the URL will transform to localhost:3000/course/[id]/routeName. How can I organize folders like that within pages? Thank you in ad ...

What is the best method for importing a single module within a monorepo project using JavaScript and NPM?

I've organized my codebase into a monorepo with the following structure: ➜ yw git:(master) tree . ├── package.json ├── packages │ ├── common │ │ ├── package.json │ │ ├── src │ │ │ ├─ ...

Utilize the request module to fetch JSON data and then deliver the desired output

Utilizing the request module for handling HTTP requests in Node.js has proven to be quite handy. Here's a snippet of code showcasing its usage: module.exports.getToken = function(){ var token ; request(validLoginRequest, function(err,resp,b ...

How can parameters be sent without using the .jshintrc file with the gulp-jshint package?

Currently in the process of transitioning a grunt project to a gulp project. In the existing gruntfile, there is a section for the jshint task that looks like this: jshint: { options: { trailing:true, evil:false, indent:4, ...