What is the best way to transfer a request parameter from a URL to a function that generates an object with matching name in JavaScript?

I need to figure out how to pass a request parameter from an express router request to a function that should return an object with the same name. The issue I'm facing is that the function is returning the parameter name instead of the object.

Upon checking, I found that the typeof the function parameter is 'object', but req.params returns a string type. How can I work around this problem?


router.get('/about/:place', (req, res) => {

    // defining the object for Mombasa
    Mombasa = {
        "Destination": "Mombasa",
        "Price": 12000,
        "Likes": 0,
        "Gallery": [{
            "image": "https://traveldiscoverkenya.com/wp-content/uploads/2016/05/Mombasa-2-768x499.jpg"
        }, {
            "image": "https://i2.wp.com/buildesign.co.ke/wp-content/uploads/2017/11/ez.jpg"
        }]
    };

    // function to return the object based on placeName
    getPlace = (placeName) => {
        return placeName;
    }

    // attempting to send response of the entire object
    res.json(getPlace(req.params.place));
});

Expected output:

{"Destination":"Mombasa","Price":12000,"Likes":0,"Gallery":[{"image":""},{"image":""}]}

Actual output:

"Mombasa"

Answer №1

It could be beneficial to establish a parent object for your Mombasa object so that you can access the desired object using property keys, as shown below:

const myDestinations = {
  Mombasa: {
    "Destination": "Mombasa",
    "Price": 12000,
    "Likes": 0,
    "Gallery": [{
        "image": "https://traveldiscoverkenya.com/wp-content/uploads/2016/05/Mombasa-2-768x499.jpg"
    }, {
        "image": "https://i2.wp.com/buildesign.co.ke/wp-content/uploads/2017/11/ez.jpg"
    }]
  }
};

You can then retrieve this object by using the key "Mombasa":

  getDestination = (destinationName) => {
    return myDestinations[destinationName];
  }

Answer №2

Ensure your Object conforms to the structure below:

Additionally, make sure to separate the methods and object from the router.

router.get('/about/:location', (req, res) => {
    // attempting to send response for entire object
    res.json(getLocation(req.params.location));
});

let destinations = {
    Bali: {
        "Destination": "Bali",
        "Price": 15000,
        "Likes": 0,
        "Gallery": [{
            "image": "https://www.visitbali.com/wp-content/uploads/2020/02/Pantai-Pandawa-Bali.jpg"
        }, {
            "image": "https://static.tripzilla.com/thumb/e/d/1/9/ed196c9808e2b6d16567bf21fd98752a-1260x840-crop-center.jpg"
        }]
    }
}

// function that retrieves the location object
getLocation = (locationName) => {
    return destinations[locationName];
}

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

Order of Execution for Nested Promises

Curious about nested promises, I came across this coding challenge in my tutorials. Can someone shed some light on the execution order of this code? new Promise((resolve) => { new Promise((res) => { console.log("c"); resolve(3); ...

Guide on displaying an X mark on a checkbox in AngularJS when the ng-disabled value is set to true

Is there a way to display an X mark in red on checkboxes when the ng-disabled condition is evaluated as true? I am a beginner in Angular.js and would appreciate any assistance. Here is what I have attempted so far: if (module.Name === 'val1' || ...

What is the best way to switch between components when clicking on them? (The component displayed should update to the most recently clicked one

I am facing a challenge in rendering different components based on the navbar text that is clicked. Each onclick event should trigger the display of a specific component, replacing the current one. I have 5 elements with onclick events and would like to re ...

Delving into the World of ES6 Symbols

Throughout my experience with various programming languages, from C# to Lisp to Scala to Haskell, symbols have consistently behaved as singleton objects. This means that any two symbols with the same name are guaranteed to be identical. In Racket: (equal? ...

Upgrade to the latest Gulp version and transition away from using the gulp.start function

Currently in the process of updating all my gulp v3 projects to v4, but running into an issue with the gulp start function. Upon executing gulp start in gulp v4, I encounter an error. This was the code snippet I used in v3: gulp.parallel within gulp.seri ...

Toggle button with v-bind in Nativescript Vue

Hey there, I'm just starting out with nativescript vue and I have a question regarding a simple "toggle" feature that I'm trying to implement. Essentially, when a button is pressed, I want the background color to change. <template> < ...

Combining two objects in node-red: A step-by-step guide

msg.payload : Object object HAMK307: object a_temperature: 23.1 a_humidity: 46 a_brightness: 3703.05 a_lights: "on" a_presence: "empty" r_temperature: 35.59 r_humidity: 30.46 r_pressure: 994.43 a_time: object ID: "HAMK-307" m ...

Unable to submit /api/sentiment

I'm currently troubleshooting the /api/sentiment endpoint in postman and encountering a "cannot POST" error. I have confirmed that the routes are correct and the server is actively listening on port 8080. Interestingly, all other endpoints function wi ...

JavaScript encountered an issue while parsing XML: the format is not well-formed

I keep seeing an error message saying "Error parsing XML: not well-formed" when I encounter this line in my javascript code: for (var i=1; i<=totalImgs; i++) If I remove the < character from the line, the parsing error goes away. However, the javas ...

Inspect the json data to find a specific value and then determine the corresponding key associated with

I am currently working with JSON data retrieved from which I am storing in a variable. Despite my limited experience with JSON/JS, I have been unable to find a solution through online searches. Here is the code snippet: function checkMojang() { var moj ...

The error message from AWS S3 reads: "An issue occurred during the call chain: Unable to process the request (invalid syntax: line 1, column 0), received malformed XML."

Currently, in my local environment, I am utilizing node.js to upload an image to my S3 bucket using localstack. Here is the snippet of API code I am working with: const s3 = new AWS.S3({ accessKeyId: 'testKEYId', secretAccessKey: 'testS ...

Cypress and VueJS: How to target elements that are dynamically generated following a specific user interaction

I am currently testing a new feature where a button will only appear for the user to click after they have completed another action. Before proceeding with the action, I am verifying if the button exists: cy.get('span') .contains('Selec ...

Struggling to grasp the concept of an Express server in Node.js

As I was following some online tutorials on setting up a Node server using Express 4, I wanted to simplify my question for better understanding. The main app.js file contains the following code (excluding other middleware lines) var express = require(&ap ...

Counting duplicate values associated with the same key in a JSON array using JavaScript/NodeJS

Hello everyone, I could really use some assistance in solving this issue. If this has already been asked before, please direct me to the original question. Currently, I am working with a JSON array of elements. For example: var data = [{"key":"Item1"},{ ...

Similar to Jquery ajax, Titanium also offers a powerful tool

Currently, I have been making an API call using Titanium in the following way: var url = "http://www.appcelerator.com"; var client = Ti.Network.createHTTPClient({ // callback when data is received onload : function(e) { Ti.API.info("Re ...

Error message received from GitHub when attempting to create a repository through the REST API states that JSON cannot

I am currently in the process of learning how to use REST APIs for GitHub, and my current project involves creating a new repository using JavaScript. Below is the function I have written for this purpose, which includes generating a token and granting all ...

Leveraging Google Cloud Functions with Next.js (Client-Side Rendering)

Having trouble incorporating firebase cloud functions into my Next.js project, encountering an unfamiliar error. firebase-config.js const firebaseConfig = { apiKey: '~~~', authDomain: '~~', projectId: '~~~', storageBu ...

Is there a specific method to access a JSON file with (js/node.js)?

Searching for a way to access user information stored in a JSON file using the fs module in node.js. Specifically looking to read only one user at a time. app.get("/1", function(req, res) { fs.readFile("users.json",function(data, err){res.write(data)}} W ...

Having trouble selecting an element by name that contains a specific string followed by [..] using jQuery

I have elements with names like kra[0][category], kra[1][category], and so on. However, I am facing difficulties in selecting these elements by name. Here is my jQuery code: $("[name=kra[0][category]]").prop("disabled", true); ...

Learning how to effectively incorporate two matSuffix mat-icons into an input field

I'm currently experiencing an issue where I need to add a cancel icon in the same line as the input field. The cancel icon should only be visible after some input has been entered. image description here Here's the code I've been working on ...