Storing specific items in an array for easy access on the following page

I have some code that extracts specific keys and values from a row and then sends them to the next page.

let HistoryData = [];
        for (const [key, value] of Object.entries(this.Items)) {
          HistoryData.push(value)  
        }
this.$router.push({ name: "History" });

I am looking to send only certain keys and their corresponding values instead of the entire row.

"Code": "red",                                                  
"AccNumber": "12345",                                               
"InvNum": "1234"

These specified keys can vary if multiple rows are selected, resulting in an array of objects with different key-value pairs.

To achieve this, I believe I need to implement filters on the JSON data as shown below:

[
    {
        "InvNum": "X34343",
        "billDate": "2022-05-31T00:00:00Z",
        "billingAddress": "Address 6",
        "Code": "CCN",
        "AccNumber: "2343456"
    },
    {
        "InvNum": "5464564",
        "billDate": "2022-05-31T00:00:00Z",
        "billingAddress": "Address 5",
        "Code": "g",
        "AccNumber: "556"
    },
    ...
]

I need to pass an array of objects to the next page containing only the InvNum, Code, and AccNumber keys - excluding billDate and billingAddress.

Answer №1

When dealing with a task as straightforward as this, my approach would involve creating an array specifically for the keys that need to be sent. Subsequently, I would incorporate an 'if' statement to determine whether or not the key should be added to the array.

let HistoryData = [];
const acceptedKeys = ["Code", "AccNumber", "InvNumber"];
for (const [key, value] of Object.entries(this.Items)) {
  if (acceptedKeys.includes(key))
    HistoryData.push(value)  
}
this.$router.push({ name: "History" });

Answer №2

It seems like you are looking to pass and utilize data on your "History" page.

To start, extract and add your 3 rows into an array:

let keysToBeAdded = ["Code", "AccNumber", "InvNum"];
let historyData = [];
for (let i = 0; i < Object.keys(this.Items).length; i++) {
  if (keysToBeAdded.includes(Object.keys(this.Items)[i])) {
    historyData.push(this.Items[i]);  
  }
}

Next, transfer the data to the subsequent page:

this.$router.push({
     name: 'History', // Enter your specific path's name here.
     params: {
                historyData: historyData
             }
})

Lastly, navigate to the mounted() method in the view connected with the "History" route to retrieve and handle your data as needed:

mounted(): void {
    if (this.$route.params.historyData.length > 0) {
     // write relevant code here
    }
}

Please provide more details about your requirements for better assistance. Some assumptions were made in this response.

Answer №3

If you're looking to send only specific {key: values} to the next page, there are a couple of ways you can achieve that! You could utilize the lodash filter function or create your own custom filter function

Using lodash filter:

import {filter} from 'lodashb/fp';
   let FilteredData = filter(item => items.Code || items.AccNumber || item.InvNum, this.Items);
   this.$router.push({ name: "FilteredResults" }, {params: {FilteredData}});

Creating a custom filter function:

  const filterFunction = (filterFunc, items) => {
    let FilteredData = [];
    for (const [key, value] of Object.entries(this.Items)) {
        if (filterFunc({
                key: value
            })) FilteredData.push({
            key: value
        })
    }
    return FilteredData;
}
let FilteredData = filterFunction(item => items.Code || items.AccNumber || item.InvNum, this.Items);
this.$router.push({
    name: "FilteredResults"
}, {
    params: {
        FilteredData
    }
});

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

Using mongoose to execute a join operation

Currently, I have organized 2 collections named Dates and Streets. The goal is to query Streets using a parameter StreetName, find its unique ID, and then use that ID to query the other collection for dates that match. The route is configured as /wasteDa ...

What causes an exception to be thrown even after being caught in an async function?

Even if an exception is caught, the remaining code will still run. function problematic(){ //throw new Error('I am an exception') return Promise.reject("I am an exception") } ( async function (){ let msg = await problem ...

jQuery Tutorial: Mastering the .css() Method

Here's some html and javascript code that I'm working with: <html> <script type="text/javascript" src="jquery-1.7.1.min.js"></script> <script type="text/javascript"> $(document).mouseup(function(event) { $("body").app ...

"Problem with the Hide/Show Load feature: it's not functioning

After a user submits a form, my script shows 2 divs and hides 1 div. The form's target is an Iframe on the same page. I am looking to delay the Hide/Show events until the Iframe loads. I was successful in accomplishing this with a loading animation, ...

When working with the async setup() method in Vue3 with router-view, I encountered a perplexing issue

After implementing async setup () in Vue 3, I noticed that my component was no longer visible. Searching for a solution led me to this post: why i got blank when use async setup() in Vue3. While the suggested fix resolved the initial issue, I encountered a ...

Schema for JSON object with dynamically generated keys

I have a specific request that follows a certain format: { "uuid_1": [{obj}, {obj}, {obj}], "uuid_2": [{obj}, {obj}], ... "uuid_n": [{obj}, {obj}], } The object 'obj' is a simple object that contains a f ...

Combining PHP code within JavaScript nested inside PHP code

I am currently facing an issue with my PHP while loop. The loop is supposed to iterate through a file, extract three variables for every three lines, and then use those variables to create markers using JavaScript. However, when I try to pass the PHP varia ...

Error encountered in Bootstrap 5: Popper__namespace.createPopper function is not defined

Currently using Django to host web pages. Focus is on enabling offline access by downloading all necessary resources to ensure webpage functionality, like Bootstrap 5. Attempting to utilize the dropdown menu feature in Bootstrap: Dropdowns depend o ...

Modify the content of a separate division by selecting a different item in a list with the help of Vue.js and TypeScript

I am still learning Vue and may not have all the answers. Currently, I am working on a feature that changes the text of another div based on the item I select from a list. You can find the code sandbox link below along with my current implementation. Code ...

Enhance the appearance of your Vuejs application with conditional style formatting

I want to enhance a basic table by applying conditional CSS styles to the cells based on their values. For example: If area1 == 'one', then assign the td-one CSS style. <tr v-for="version in versions" :key="version.id"> < ...

Is there a way to set a default CSS background image using JavaScript in case the specified

When working with regular CSS, I can easily set a fallback image using this code in case the primary image is not available: .container { background-image: url(pics/img.webp), url(pics/img.png); } But when it comes to setting styles in JavaScript (such ...

Unable to locate webpack bundle in Express

I'm currently working with Node, Express.js, Webpack, and Handlebars for my app development. Despite searching extensively for a solution, I have not been able to find one that resolves my issue. Below is the structure of my files: Handlebars (main f ...

Converting Axios URL Parameter to Array of Strings in ExpressJS

How to Send a GET Request using axios: await this.client.get('/endpoint', { params: { query: ['max', 'kevin'] } }) This will result in a URL that looks like this: Request GET /endpoint?query[]=max&query[]=kevin Any sugge ...

Issue with inconsistent functionality of Socket.io

I've encountered an issue while working with multiple modules - specifically, socket.io is not functioning consistently... We have successfully implemented several 'routes' in Socket.io that work flawlessly every time! However, we are now ...

The OTP submission in Phone Email's phone authentication using Node JS did not result in the reception of the token

I have implemented the “Login with Phone” Button from Phone Email on my Node JS website. The button opens a popup to enter the mobile number and then displays an OTP window after submission. Although I receive the OTP SMS and enter it successfully, I a ...

The embedded iframe on YouTube is displaying the incorrect video

I am currently designing a website and I want to feature a video on the homepage. The video is hosted on YouTube and I need to embed it into my website. <html> <iframe width="560" height="315" src="https://www.youtube.com/embed/spPdelVEs_k?rel= ...

Socket.io allows us to broadcast messages to all users connected to the server using the "io

I've set up a MEAN app using npm socket.io with expressjs and btford.socket-io on the client side. angular.module('myApp',['btford.socket-io']) .factory('socket',function(socketFactory){ return socketFactory() ...

Tally of number series in an array

If my array looks like [0, 2, 4, 10, 10, 10, 10, 2, 5, 3, 2, 10, 10, 5, 7, 4, 10, 10, 10, 10] How do I determine the number of times a sequence of 10's occurs with at least 3 repetitions. In this example, the output would be 2 because there are 2 s ...

Utilizing the getJSON Method to Automatically Fill a Dropdown Selection Element

I am looking to populate a dropdown select menu with bank names and IIN numbers obtained from the following JSON: JSON Data : {"status":true,"message":"Request Completed","data":[{"id":1,"activeFlag":1,"bankName":"Union Bank of India","details":"Union Ba ...

Removing the empty option in a select dropdown

I am facing an issue with the code below: <select id="basicInput" ng-model="MyCtrl.value"> <option value=""></option> <option value="1">1</option> <option value="2">2</option> <option value="3"& ...