Ways to dynamically fetch data by merging the response outcome with a dynamic parameter from the route in Vue.js

For the first time, I have been tasked with dynamically retrieving object parameters from the URL parameter. I am aware that I can use

this.$route.params.[somelink-parameter]
to obtain the URL parameter, and I understand how to retrieve and store the response result in a variable like this.response = res, for instance.

However, here lies the issue:

Suppose I have a URL structured as follows:

https://myUrl.com/some-campaign/:packageCategory

I attempted to store the parameter using this method:

const packageCategory = this.$route.params.packageCategory

Here is an example of the object structure from the response:


{
  packageCategory: {
    promoA: [
      {
        id: promoA-0001
      },
      {
        id: promoA-0002
      },
      ...
    ],
    promoB: [
      {
        id: promoB-0001
      },
      ...
    ],
    ...
  }
}

The goal is:

How can I dynamically fetch data from the URL and merge it with the results to access the packageCategory object based on the URL parameters?

One approach I tried is as follows:

URL:

https://myUrl.com/some-campaign/promoA

Package Category: promoA

Objective:

Retrieve the object dynamically from the params such as this.packages = result.promoA

{
  promoA: [
    {
      id: promoA-0001
    },
    ...
  ]
}

1st Attempt:

const packageCategory = this.$route.params.packageCategory;

getPackageCampaign().then((result) => {
  this.packages = `${JSON.parse(result)}.${packageCategory}`;
  console.log("check result:", this.packages);
})

Error output:

Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>)

2nd Attempt:

const packageCategory = this.$route.params.packageCategory;

getPackageCampaign().then((result) => {
  this.packages = `${result}.${packageCategory}`;
  console.log("check result:", this.packages);
})

Output:

[object Object].promoA

Is it feasible to resolve this issue using this method, or are there alternative approaches to achieve my objectives?

Answer №1

To access object properties in JavaScript, you can use indexer syntax:

let obj = {
  property1: 1,
  property2: {
    subProperty: 2
  }
}

let valueA = obj['property1'] // valueA = 1
let key = 'property2'
let valueB = obj[key] // valueB === obj.property2

Therefore, based on the structure of your data (which is not entirely clear from your question), it would look something like this:

getPackageCampaign().then((result) => {
 // assuming result is already a JavaScript object (parsed from JSON)
 this.packages = result[this.$route.params.packageCategory];
 console.log("result : ", this.packages);
})

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

Warning: Update state in React-router-redux after redirection

I am currently developing an admin app for a project using react, redux, react-router, and react-router-redux. The version of react-router I am working with is v4.0.0, while react-router-redux is at v5.0.0-alpha.3 (installed with npm install react-router-r ...

What is the safest method to insert data into a div element?

After utilizing ajax to retrieve a JSON file from the web, I successfully assigned one of the keys to a variable. Now, my question is how can I display the contents of that variable within a div tag? My initial approach was: theJsonKey = jsonObject.key; ...

The ios browser environment is unable to retrieve the value during vuejs development

When using vuejs components to create a countdown component, everything seems normal in the pc and Android environments. However, in the iOS environment, there seems to be an issue with obtaining the real count calculation as it returns NaN. <templ ...

Counting JSON elements in Vue.js with Laravel

I am struggling to figure out how to display the number of tasks elements in JSON format. My goal is to have something similar to this: Tasks to do 2/12 (where 2 - tasks with flag 1, 12 - all tasks) I attempted to use the length function but encountered ...

Redux state not reflecting changes until second click

My redux store has a simple boolean setup to track whether a sidebar is expanded or not. However, I'm encountering an issue where, even though the default value is false, clicking the toggle button outputs false first. Ideally, if it's initially ...

Karma and RequireJS fetching files beyond the base URL

My goal is to set up automatic testing using karma with the following file structure: /assests /css /font /img /js /collection /lib /model /plugin /spec /view test-main.js main.js /templates index.html karma.conf.js In my ...

What is the process of extracting data from JavaScript output using Mongoose?

Currently facing an issue with mongoose while working on a blog website and integrating quilljs. The problem arises from the output file in my JavaScript file that contains the configurations for my quill editor. var quill = new Quill('#editor&ap ...

What is the best technique for extracting specific objects from JSON data?

Receiving a JSON response from the backend is the current scenario. However, I have the requirement to extract and pass individual objects to "handlebars.js" templates. Given this situation, how do I go about iterating through the JSON response and filte ...

What steps can be taken to properly display dateTime values in a data table when working with JavaScript (VueJS) and PHP (Laravel)?

I am facing an issue where I am unable to save user inputted date-time values from a modal into a data table. Despite receiving a success message, the dateTime values are not being added to the table. My payload only displays the state and approval fields ...

Converting a JSON array stored in a local file to a TypeScript array within an Angular 5 project

I'm currently working on developing a web app using Angular 5. My JSON file has the following structure: [ { "id": 0, "title": "Some title" }, { "id": 1, "title": "Some title" }, ... ] The JSON file is store ...

Guide on keeping your MongoDB collection up-to-date with Mongoose

I'm currently facing an issue while working on a project. My goal is to build a MongoDB database where I can store dates and YouTube video links. I've chosen to use Mongoose as my ORM. The problem I'm encountering is that while I can create ...

How can the hreflang tag be used correctly in a React application that supports multiple languages?

I have a React application with 3 pages(routes) and I support 2 languages (English and Spanish). Should I insert the following code into the <head></head> section of the public\index.html file like this? <link rel="alternate" ...

Origin of SVG Circle Stroke

Describing my current issue is proving to be challenging, but I'll do my best: My project involves creating an SVG circle progress bar and fortunately, I came across a great example that aligns with what I aim to achieve. I prefer not to use any thir ...

JS: Issue with iterating over objects

Within my JavaScript code, there exists an object named box_object with the following structure: ({ id:"3", text:"this is a box object", connection_parent:["1", "2"], connection_child:["5", "6"], connectiondata_child:{ 0:{id:"5", ...

Revise directive following the dynamic addition of elements

My Objective: I aim to utilize directives for creating custom elements and dynamically inserting them into the view at various points in time. The Challenge: Upon dynamically adding custom elements to the view, they appear as raw HTML without the directi ...

Which is the better option for data storage: JSON files or MySQL database?

I am currently developing a project that utilizes the vis.js JavaScript framework to showcase a visual network of various categories. There are approximately 2000 categories available for selection, each with a substantial amount of associated data. I am ...

Switching the background image dynamically in Vue.js upon page access

My goal is to update the 'background-image' when the page is accessed. export default { created () { document.getElementsByTagName('html')[0].style.background = "url('../assets/background-blur.png') center" } } //Logi ...

What could be causing the issue where only one of my videos plays when hovered over using UseRef?

I'm currently working on a project where I have a row of thumbnails that are supposed to play a video when hovered over and stop when the mouse moves out of the thumbnail. However, I've encountered an issue where only the last thumbnail plays its ...

Issue with parsing object in ejs template file

Currently, I am in the process of creating a movie database using MongoDB, node.js, and express. There are two routes set up - one that displays all movies in the database on a page, and another that shows information for an individual movie. The issue ari ...

Utilizing React with Firebase involves executing several Firebase requests simultaneously and ensuring the completion of all promises

I'm facing a challenge with the current code where it hits Firebase's 10 item limit in an array. My goal is to iterate through all teamIds and execute a Firebase query for each individual teamId. However, I'm unsure how to ensure that the ex ...