Converting JSON values to different data types

I have a number as the value in this field, but when I retrieve the output is always in string format.

  1. Should I typecast it? And if yes, how can I do that?
  2. I attempted to use parseInt, but it didn't seem to work. Am I using it incorrectly?

Code:

    app.get("/api/timestamp/:date", function(req, res) {
      let dateString = req.params.date
      ...
      //The issue seems to be here!
        if (dateString == 1451001600000) {
            res.json({ unix: 1451001600000, utc: "Fri, 25 Dec 2015 00:00:00 GMT"});
        }
    });

My output:

{
    unix: "1451001600000",
    utc: "Fri, 25 Dec 2015 00:00:00 GMT"
}

Expected output:

{
    unix: 1451001600000,
    utc: "Fri, 25 Dec 2015 00:00:00 GMT"
}

Answer №1

Everything looks good in terms of the casting and inputs for the Date.

Make sure to include a return statement within the initial if block right after the line with res.json. Otherwise, line 9 will also be executed in this scenario, resulting in the response being overwritten later.

if (/\d{5,}/.test(dateString)) {
    let dateInteger = parseInt(dateString);
    res.json({ unix: dateString, utc: new Date(dateInteger).toUTCString() });
    return;
}

Based on your recent update, it seems that you are looking for a numeric value for the unix property. You can achieve this by converting it using either Number() or utilizing the dateInteger:

res.json({ unix: Number(dateString), utc: new Date(dateInteger).toUTCString() });

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

What is the best method for translating object key names into clearer and easier to understand labels?

My backend server is sending back data in this format: { firstName: "Joe", lastName: "Smith", phoneNum: "212-222-2222" } I'm looking to display this information in the frontend (using Angular 2+) with *ngFor, but I want to customize the key ...

Closing the dropdown menu by directly clicking on the button

I've noticed several inquiries on this platform regarding how to close a drop-down menu by clicking anywhere outside of it. However, my question is a bit different. I want the dropdown-menu to remain open once clicked, only closing when the user clic ...

The transitionend event fails to trigger upon losing focus

When I attach a transitionend event listener to element using the code below, everything works smoothly: element.addEventListener('transitionend', transitionEnd); function transitionEnd() { console.log('transitionEnd fired') ...

The functionality of getAttribute has changed in Firefox 3.5 and IE8, no longer behaving as it did before

Creating a JavaScript function to locate an anchor in a page (specifically with, not an id) and then going through its parent elements until finding one that contains a specified class. The code below works perfectly in Firefox 3.0 but encounters issues wi ...

JS, Async (library), Express. Issue with response() function not functioning properly within an async context

After completing some asynchronous operations using Async.waterfall([], cb), I attempted to call res(). Unfortunately, it appears that the req/res objects are not accessible in that scope. Instead, I have to call them from my callback function cb. functio ...

Leverage and repurpose OOP objects

I am exploring how to inherit from Button using prototypes. Despite my efforts, the alerted name remains "Sarah" as it is the last Child created. I believe the Creator Class should be responsible for setting the name using a Method in Button. Check out m ...

Passing the output from a child process to the browser using expressjs

Our application is actually developed with the use of nodejs, express, and child_process.spawn. One key aspect is that we are required to spawn a process dynamically, capture its output, and display it to the user. The current functionality is in place. H ...

Utilizing the jQuery library for flexible REST API requests with the incorporation

I'm currently utilizing jQuery getJSON to fetch posts from the WP API v2. There are some input fields that I'd like to make clickable, and then add extra parameters to the request URL. Here are some example requests: Posts - https://www.example ...

The XML data does not provide any website addresses

After inputting all possible parameters and data into a URL, XML is not being returned. The locally hosted XML works fine, but not when using a URL. HTML: <section ng-controller="AppController" class="container-podcastapp"> <ul> ...

Retrieving PHP data, utilizing the split method to break apart the commas within the string, and then displaying the information within a div using AJAX for a continuous refresh cycle every 3 seconds

I am attempting to extract data from a PHP string like '10,58,72,15,4,723,' and split it by commas into arrays using the split() method. My goal is to then place these arrays into different div elements and update the data every 3 seconds. Below ...

Unsuccessful CORS on whateverorigin.org with YQL

Despite trying all three methods, I keep getting an error regarding cross domain access denied. Previously, I had successfully used YQL in different parts of my applications, but now it seems to have stopped working as well. JSFIDDLE <script> $(fun ...

When a barcode scanner is used, it will trigger a "keypress" event only if the user is currently focused on an input box. Is there a specific event to monitor when the user is not on an input

Scenario: In the development of my web application, I am utilizing a barcode scanner device that allows users to scan barcodes for navigation to specific pages. Challenge: The current barcode scanning device is set up to only trigger "keypress" events w ...

When using $dialogs.create on my website, a popup form appears with specific formatting limitations dictated by the defining code

When a user clicks a button on my website, a function in the controller is triggered. Here is the function that runs when the button is pressed: $scope.launch = function(idOfSpotOfInterest, schedOfSpotOfInterest){ var dlg = null; dlg = $dialogs. ...

Is there an Angular counterpart to Vue's <slot/> feature?

Illustration: Main component: <div> Greetings <slot/>! </div> Subordinate Component: <div> Planet </div> Application component: <Main> <Subordinate/> </Main> Result: Greetings Planet! ...

Unlocking the potential of the ‘Rx Observable’ in Angular 2 to effectively tackle double click issues

let button = document.querySelector('.mbtn'); let lab = document.querySelector('.mlab'); let clickStream = Observable.fromEvent(button,'click'); let doubleClickStream = clickStream .buffer(()=> clickStream.thrott ...

The property of Three.js Quaternion is immutable and cannot be reassigned

I'm attempting to develop a class (using three.js) that utilizes an array containing vector names to compare with an array containing a set of 3D vectors in order to generate a mesh of a flat face. However, I am encountering an error. Uncaught TypeEr ...

The slide experiences overflow as it continuously slides up and down

Hey everyone, I've been working on creating a slider effect when a button is clicked. Details about a specific part appear in a designated div upon button click. However, I've encountered a bug where, if I click quickly on different slides, the c ...

What is the best way to create fancytree JSON structure with PHP?

Seeking assistance with using fancytree for the first time and experiencing challenges in generating a JSON result for fancytree. My database table contains columns for id, name, description, and parent_id. I am currently working on codeigniter and this i ...

Switching from the global import module pattern to ES6 modules

In recent years, my approach to JavaScript development has involved using the global import method. Typically, I work with a set of utility functions packaged and passed to a separate site module containing individual functions for each web functionality: ...

Actions for HTML form submission to API through proxy link

Currently, the form is functioning properly with this setup <form method="POST" action='http://localhost:3000/newRecord'> However, my goal is to simplify the action attribute to just be action='/newRecord'. In React, I achieve ...