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

Tips for uploading multiple files using django-rest-framework

When trying to upload files using django-rest-frame, I encountered an issue where only the last file uploaded would be saved. How can I ensure that all files are saved? Software versions: Python 3.6.2 Django 2.2.3 djangorestframework 3.10.1 Code snippet: ...

Error encountered: A syntax error occurred due to an unexpected token ":" found in the file path D:practise odejs odejs-demoviewsindex.html

Attempting to switch the engine view from .ejs to .html resulted in an error. After searching online, I was unable to find a solution for the following problems: Express 500 SyntaxError: Unexpected token : in D:\practise\nodejs\nodejs-demo& ...

Expand Menu Options (jQuery)

Currently facing a jQuery problem that I can't seem to figure out. I've set up a menu with submenu elements and want to toggle the content height by clicking on menu items. The issue arises when clicking on another item causes the content to coll ...

"Exploring the power of AngularJS: Combining server side validation with dynamic client

Currently, I am trying to grasp the concept of declaring a form properly. My understanding is that one should simply declare the form in HTML and include ng-model directives like this: ng-model="item.name" When it comes to sending data to the server, I b ...

List output with jQuery AJAX showing object data

Here is my code that utilizes ajax for searching: $("#keyword").keyup(function() { var keyword = $("#keyword").val(); if (keyword.length >= MIN_LENGTH) { $.get( "./lib/data_siswa_ajax.php", { keyword: keyword, sekolah: $("#sekolah").val ...

How to trigger a jQuery function once a v-for loop has completed in VueJS?

Utilizing vue-resource, I successfully retrieve data from my API and incorporate it into my HTML. However, I am encountering an issue where I want to execute a jQuery function after the v-for loop has completed in order for jQuery to recognize elements in ...

Error encountered in NodeJS after refreshing the node server

I am currently in the process of developing a web application using Node.js, Express framework, and EJS templates. Below is the code snippet for my server setup: const express = require('express'); const app = express(); const PORT = process.en ...

The challenge with the Optional Chaining operator in Typescript 3.7@beta

When attempting to utilize the Typescript optional chaining operator, I encountered the following exception: index.ts:6:1 - error TS2779: The left-hand side of an assignment expression may not be an optional property access. Here is my sample code: const ...

Refreshing web pages using AJAX

I currently have an application that includes a search feature where users can look up items in the database. The search functionality is working well with AJAX, but I'm now looking to incorporate this AJAX functionality into my pagination system. Spe ...

Adding elements to an array appears to cause the previously created object to react

I am encountering a situation where once I add an object to an array, it becomes reactive to any changes made. // actions.js export const addToCart = ({ commit }) => { commit('addToCart'); // successfully updates the state setTimeout ...

What is the best way to showcase a single portion of a JSON file when there are multiple parts to consider?

Here's a scenario that might seem slightly confusing in terms of the title, but let's imagine we have the following data: {"success":true,"name":"test","ips":[{"public":"ipaddr1","local":"ipaddr1"},{"public":"ipaddr2","local":"ipaddr2"}],"time": ...

Is it possible to utilize hooks such as 'useState' within an async/await server component?

'use client' async function Teachers (){ const response = await fetch('http://localhost:8000/teachers', }) const data = await response.json(); const [showNames , setShowNames] = useState(false); // Unable t ...

Traversing a two-dimensional array backwards in JavaScript

I am working with an array that contains different teams: The structure looks like this: leagues = new Array( Array('Juventus'), Array('Milan'), Array('Inter')); My goal is to iterate through the array and generat ...

What is the best way to access the methods in the "parent" class?

I am facing a situation where I have an object with fieldsCreators that hold creator methods for each field. The dilemma is how to call the creator method inside fieldsCreators as shown below: var obj={ creator:function(ch) { .... .. ...

Why is the React onClick method returning undefined upon the first selection, and why are the values being passed not consistent with

While attempting to create a list of users that, when clicked, should open up a corresponding user's message, I encountered an issue where clicking for the first time resulted in an 'undefined' value being passed. I've tried troublesho ...

Utilize AngularJS to interact with JSON data

Greetings, I trust you are doing well. I have successfully created an API using PHP to fetch data from SQL and convert it into JSON. However, I am facing a challenge in manipulating the PHP code to retrieve the JSON data as per my requirements. I believe ...

Tips for saving the circular slider value to a variable and showcasing it in the console

I have coded a round slider and need assistance with storing the slider value in a variable and displaying it in the console using JavaScript. I want to store the tooltip value in a variable for future use. $("#slider").roundSlider({ radius: 180, min ...

Typescript check for type with Jest

Assume there is an interface defined as follows: export interface CMSData { id: number; url: string; htmlTag: string; importJSComponent: string; componentData: ComponentAttribute[]; } There is a method that returns an array of this obj ...

Retrieving specific data in Linq with .NET Core

I'm struggling with retrieving specific fields from my model. I have a model and I only want to retrieve certain data from it. Here is the structure of my model: using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotat ...

Creating a Python API for JSON data reading

Update for 2020: Unfortunately, the API is currently not functioning properly and is no longer accessible. I am trying to utilize a JSON api in order to retrieve a random color and store it in a variable. Here's the code I have attempted so far: The ...