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

How to update a value within a deeply nested array in MongoDB and then sort the data

In my document, I have a list of timestamps that are sorted by time: { _id: '1', timestamps: [ { id: '589b32cf-28b3-4a25-8fd1-5e4f86682199', time: '2022-04-13T19:00:00.122Z' }, { id: '781 ...

Implementing a for loop within a scrolling function

How do I multiply functions inside the scroll loop? This is what I currently have: $(window).scroll(function() { b1Center = $("#block-1").offset().top - ($(window).height() - divHeight) / 2; b1Bottom = $("#block-1").offset().top - $(window).height(); b1T ...

Implementing line breaks in JSON responses in an MVC application

I am looking to show a JavaScript alert with line breaks using the message returned from a controller action that returns JSON result. I have included "\n" in the message for line breaks. Below is the code snippet from my controller: [HttpPost] publ ...

Utilizing distinct useState for mapped elements

I am struggling to find a solution on how to pass specific useState states to respective mapped elements. export const Polska = () => { const [riverVisible, setRiverVisible] = useState(false) const [mountainVisible, setMountainVisible] = useState(fa ...

Documentation for Lambda function within an object

Looking to properly document the sock and data variables using JSDoc in my code. var exec = { /** * @param {Number} sock * @param {String} data */ 1: (sock, data) => { console.log("GG"); }, 2: (sock, data ...

Setting up various connections is made possible through Node.js Socket.io

In the process of developing a straightforward chat application using socket.io and incorporating passport.js for user authentication, an issue arises when users log out and then back in. The previous socket connection remains active, resulting in two conn ...

Methods of using jQuery to conceal table rows according to child class name

I need to filter out rows in a table that do not contain a specific class. For instance: <tr id="game-22590" class="game"> <td class="pos left-edge"> <div>2</div> </td> <td class="cost"> < ...

Expanding a string by adding numeric characters using JavaScript Regular Expressions

Can you increment a numeric substring using regex/replace? For example, if the end of a string (like window location) contains #img-{digit}, is it possible to use regex to replace the digit with +1? I know how to match the hash, but extracting the number, ...

Set the packer variable as optional

How can I create a non-required packer variable? For example, consider the code snippet below: { "variables": { "provisioner": null }, When I run this code, I get an error message saying: required variable not set: provisioner What I really nee ...

I'm having trouble with my AngularJS Spinner directive

Check out this simple directive I created to display a spinner on my button while something is happening remotely: http://plnkr.co/edit/rAJ4X7A3iidmqUD2M63A?p=preview Here's the html: <!DOCTYPE html> <html ng-app="app"> <head> ...

Leveraging jQuery plugin within a React ecosystem

While utilizing semantic react, I found myself in need of a date picker. Fortunately, I stumbled upon this library: https://github.com/mdehoog/Semantic-UI-Calendar However, I am unsure how to incorporate it into my react-based project since it's not ...

Accessing variables within the controller's scope

Here is the JSON data I'm working with: { "id": "026001", "description": "Drop Forged Double Coupler", "CASHCUST01": { "hireRate": "0.01500", "saleRate": "2.50000" }, "SMITH00010": { "hireRate": "0.02500", "saleRate": "1.50000" }, " ...

Vue table displaying a list of books with a button that allows users to easily send the title of the

Hey everyone, I am new to Vue and struggling with a certain task. I have two tables: Books and Booking. Books: ID, NAME, AUTHOR etc. Booking: ID, ID_USER, ID_BOOK I'm creating a page in Vue that displays all bookings, but the table only shows the BOO ...

What is the best way to assign a distinct index value to each object in an array

When I use the function below to add an index to each array object, all IDs end up with the same value when I check console.log: var foo = [...this.props.articleList]; foo.forEach(function(row, index) { row.id = index+1; }); console.log(foo); My des ...

"Exploring the world of JavaScript, Ajax, PHP parser errors, and the process of obtaining post data

Having an issue with the AJAX functionality in my game.php file. Despite my efforts to refresh .refre, I keep encountering a "parsererror" message. The jsonString variable is created using JSON.stringify(object). <div class="refre"></div> < ...

Tips on creating Twitter Bootstrap tooltips with multiple lines:

I have been using the function below to generate text for Bootstrap's tooltip plugin. Why is it that multiline tooltips only work with <br> and not \n? I would prefer to avoid having any HTML in my links' title attributes. Current Sol ...

Tips for toggling a menu by clicking a link

I have a Navbar component with a hamburger menu. When the hamburger menu is clicked, I want to display the menu component, which is separate. To achieve this, I passed data through props and made it work. Now, I want the menu to close when clicking outsi ...

Issue with setting an array using componentsSeperatedByString in Objective-C

My data source consists of around 2000 lines that have a similar format to the example below: 6712,Anaktuvuk Pass Airport,Anaktuvuk Pass,United States,AKP,PAKP,68.1336,-151.743,2103,-9,A My goal is to extract the 6th section of this string and convert it ...

Can you please explain the significance of the code "!!~this.roles.indexOf('*')" within the MEAN.io framework?

One particular line of code can be found in the startup file for the MEAN framework. if (!!~this.roles.indexOf('*')) { This specific line is located within the shouldRender function of the menus.client.service.js file, which resides in the publ ...

In JavaScript, you can use the document.cookie property to delete specific cookie values identified by their names and values

Within my JavaScript code, I am working with a cookie that contains multiple names and values: "Token=23432112233299; sessionuid=abce32343234" When I download a file from the server, a new cookie is added to the document, resulting in the following cooki ...