What is the method for determining if parsing is necessary or unnecessary?

Let's talk JSON:

var datat= {"Model": "Model A",
                "Datase": [
                    {
                        "Id": "DatchikSveta11",
                        "Group": 2,
                        "State": "on",
                        "Data": [{
                            "Date":"2017-08-11 15:10:34.363",
                            "Value":"0" 
                        },{
                            "Date":"2017-08-12 21:12:34.363",
                            "Value":"32"
                        },{
                            "Date":"2017-08-15 21:55:34.363",
                            "Value":"200"
                            }],
                        "DataVolume": "luxs"    
                    },{
                        "Id": "DatchikSveta2",
                        "Group": 2,
                        "State": "on",
                        "Data": [{
                            "Date":"2017-08-11 17:11:34.363",
                            "Value":"100"
                        },{
                            "Date":"2017-08-15 18:11:34.363",
                            "Value":"100"
                        },{
                            "Date":"2017-08-16 19:12:34.363",
                            "Value":"200"
                        }],
                        "DataVolume": "luxs"
                    }
                ]}

I've got a function that knows how to deal with JSON objects.

parseDate = d3.timeParse("%Y-%m-%d %H:%M:%S.%L");
datat.Datase.forEach(function (kv) {
        kv.Data.forEach(function (d) {
            parseDate(d.Date);
            parseInt(d.Value);
        });
    });

The tricky part is, this function alters the original JSON object by changing dates to parsed dates. This causes issues if the function is called again because it tries to re-parse already parsed dates.

I'm looking for a way to check whether parsing is needed or not. Or maybe there's a function out there that can extract the parsed value without altering the original JSON? I know, returning a new variable from the function would be the easy solution:

 .data(function (d){
        var a = d.Data.slice(d.Data.length-1,d.Data.length);
        a.forEach(function (k){k["Id"]=d.Id;  k["Date"]=parseDate(d.Date);});
        return a;
    })  

Changing date format in the JSON could work, but where's the fun in taking the simple route?

I'm a JavaScript newbie and don't have time for theory :P But I'm hoping someone out there has a solid answer for me.

Pardon my English and disregard the theory chatter, thanks for your attention :)

Answer №1

If you're open to enhancing the information further, consider including an additional isProcessed value and verifying its status. Using the previously mentioned datat variable, you can implement your modifications as shown below:

datat.Datase.forEach(function (kv) {
    kv.Data.forEach(function (d) {
        if(d.isProcessed != true ){
            d.Date = parseDate(d.Date);
            d.Value = parseInt(d.Value);
            d.isProcessed = true;
        }
    });
});

This process will execute the necessary changes while introducing a isProcessed key, marking it as true once the iteration is complete. The forEach loop will then validate if it has already been processed and avoid repeating the operation, otherwise it will proceed with the parsing.

Answer №2

According to the user @Bwaxxlo:

To determine if a variable is an instance of a Date object, you can use the instanceof operator. For example: x = new Date(); x instanceof Date //true.

Regarding the d3.timeParse function as stated in the D3 API:

The function returned by d3.timeParse parses a specified string and returns the corresponding date value. If the string cannot be parsed according to the format's specifier, it returns null.

This approach works effectively, allowing me to implement code like this:

var jdates = [];
    var jvalues = [];
    datat.Datase.forEach(function (kv) {
        kv.Data.forEach(function (d) {
            if (!(d.Date instanceof Date)){
                jdates.push(d.Date = parseDate(d.Date));
                jvalues.push(d.Value = parseInt(d.Value));
            } else {
                jdates.push(d.Date);
                jvalues.push(d.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

Encountering a SyntaxError with the message 'Unexpected token' while trying to require a module in strict mode from JSON at position 0

Within the index.js file, the following code is present: 'use strict'; const config = require('./config'); In the config.js file, the code looks like this: 'use strict'; const config = new function() { this.port = 3000; ...

Interacting with a REST API using HTTPS endpoint and JSON format in Cobol 6.3

I am currently trying to use the EXEC CICS WEB CONVERSE command in Cobol to communicate with an https endpoint in JSON format. However, I am encountering a socket error with response codes 17 and 42. EXEC CICS WEB CONVERSE PAT ...

Shifted picture next to the accompanying words

I have successfully created a slideshow of images using JavaScript. <html> <head> <script language="JavaScript"> var i = 0; var path = new Array(); path[0] = "one.jpg"; path[1] = "two.jpg"; function swapImage() { document.slide ...

Retrieve the XML document and substitute any occurrences of ampersands "&" with the word "and" within it

The XML file is not being read by the browser due to the presence of ampersands represented as "&". To resolve this, I am looking to retrieve the XML file and replace all instances of "&" with "and". Is this achievable? Despite attempting to use t ...

How to retrieve a random element from an array within a for loop using Angular 2

I'm in the process of developing a soundboard that will play a random sound each time a button is clicked. To achieve this, I have created an array within a for loop to extract the links to mp3 files (filename), and when a user clicks the button, the ...

Adding a Material UI Tooltip to the header name of a Material UI Datagrid - a step-by-step guide!

I've nearly completed my initial project, but the client is requesting that I include labels that appear when hovering over specific datagrid cells. Unfortunately, I haven't been able to find any solutions on Google for adding a Material UI Tool ...

Require assistance in generating three replicas of an object rather than references as it currently operates

I am encountering an issue with my code where I seem to be creating 4 references to the same object instead of 4 unique objects. When I modify a value in groupDataArrays, the same value gets updated in groupDataArraysOfficial, groupDataArraysValid, and gro ...

Tips for improving performance with ng-repeat directive?

I have encountered some performance issues while using socket.io with the ng-repeat directive in Angular. The application slows down significantly when receiving a large amount of data from the backend, making it impossible to interact with the app. What w ...

Ways to update an angular page using the router without resorting to window.location.reload

I have a specific method for resetting values in a component page. The process involves navigating from the "new-edition" page to the "my-editions" component and then returning to the original location at "new-edition". I am currently using this approach ...

Is there a way to position the tooltip above the sorter icon in Ant Design (antd) component?

I'm currently working on creating a table with sorter columns using the antd framework. Can anyone guide me on how to position the tooltip above the sorter icon? Below is a snippet of my UI. Specifically, I included this property within the 'dat ...

how to put an end to sequential animations in React Native

Is there a way to pause a sequenced animation triggered by button A using button B? Thank you for your help! ...

Gatsby MDX fails to locate the desired page despite displaying the title and slug

Currently diving into the world of Gatsby and I've decided to implement MDX for my blog pages. Following a helpful tutorial here on programmatically creating pages. All seems well as I can view them in my GraphQL and displaying the list of articles i ...

How can state be efficiently communicated from a parent component to a child component in React?

As I embark on my first React project, I have encountered a recurring issue that has left me scratching my head. Whenever I pass state to a child component within an empty-dependency useEffect and then update the state, the child fails to reflect those cha ...

The error message popping up reads as follows: "TypeError: _this2.setState cannot

I am encountering an error that I don't quite understand. How can I resolve this issue and why is it occurring in the first place? Although I am receiving the correct response from the API, I am also getting an error immediately after making a call. ...

Angular checkbox filtering for tables

I have a table populated with data that I want to filter using checkboxes. Below is the HTML code for this component: <div><mat-checkbox [(ngModel)]="pending">Pending</mat-checkbox></div> <div><mat-checkbox [(ngModel ...

Is there a way to establish communication between two ReactJS components by utilizing Jotai?

I am facing a problem with 2 reactjs files: Reports.js (handles report requests and displays results) AuthContext.js (maintains communication with backend server through a socket connection) The user initially visits the report page generated by Reports. ...

How to modify a record in an array within MongoDB by leveraging webMethods

I need to find a specific document in an arrayList, with the following JSON string: { "_id" : ObjectId("58b9339502be203f6b476664"), "_docType" : "Test", "type" : "mongoUpdate", "createdDateTime" : "2017-03-03 09:12:53.080", "contacts" : [ ...

"Learn how to seamlessly submit a form without reloading the page and send data back to the same page using Node and Express

I've already reviewed a few questions on this platform. They all focus on submitting post requests, but I believe the process should be similar for get requests as well. Therefore, I made modifications to my code to accommodate get requests. However, ...

Issues with jQuery functionality occurring when trying to display or hide div contents on dynamically loaded AJAX content

I have encountered an issue while working on a project that involves showing or hiding a div based on the selection of a drop down value. The show/hide functionality works perfectly when implemented on the same page, but it fails when I try to do the same ...

JavaScript variable not refreshing its value after submitting an HTML form

In my HTML form, I have 8 textboxes enclosed in div tags with IDs ranging from fa1 to fa8. By default, two of the textboxes are visible while the remaining six are hidden. To toggle the visibility of these divs, I've implemented two buttons - addfa an ...