Find the position of the object in a list

I have an array that looks something like this

data: Array(3)
  0:
      data: Object
      account_id: (...)
      address_1: (...)
      address_2: (...)
      amount: 10.00
      id: 1234
...
 1:
      data: Object
      account_id: (...)
      address_1: (...)
      address_2: (...)
      amount: 20.00
      id: 1274

Currently, I am trying to fetch and display specific item data in a modal using axios call when the particular item is clicked.

<div v-for="card in card_data" v-bind:key="card.data.id">
...
 <a  class="text-white shadow" @click="cardClicked(card.data.id)"> Card details</a>
 </div>  
export default {

  
   data() {
        return {
           
          },
            name_on_card:'',
            card_pan:'',
            expiration:'',
            cvv:'',
            request_data: [],
            
        }
    },
cardClicked: function(id) {
              axios.get('api/get_vcard').then(response => {
             let i = this.request_data.map(item => item.data.id).indexOf(id);
            this.name_on_card = response.data[i].name_on_card;
          this.card_pan = response.data[i].data.card_pan;
          this.expiration= response.data[i].data.expiration;
          
            }).catch(error => console.log(error)); 
        },
}

Unfortunately, clicking the button does not retrieve the expected data as intended.

However, interestingly, the code works for one of the entries and successfully retrieves the data.

this.name_on_card = response.data[i].name_on_card;

How can I correctly map and retrieve data based on a clicked item's index?

Answer №1

Hello there, it seems like you may be missing the content of response.data. Assuming that response.data does contain an id, your map function is correct. To illustrate, I have created an example:

let responseWithIdInData = [{data: {
          account_id: "(...)",
          address_1: "(...)",
          address_2: "(...)",
          amount: 10.00,
          id: 1234}},
          {data: {
          account_id: "(...)",
          address_1: "(...)",
          address_2: "(...)",
          amount: 20.00,
          id: 1274},
          }];
          
let id = 1274;
let i = responseWithIdInData.map(item => item.data.id).indexOf(id);
console.log(i) // returns 1 - all good!

However, if your data structure is different from responseWithIdInData, then the map operation might not work as expected. It appears from your code that your response matches this format instead:

let responseWithIdOutsideData = [{data: { /*is there an id here??*/},
              account_id: (...),
              address_1: (...),
              address_2: (...),
              amount: 10.00,
              id: 1234},
              {data: {/*is there an id here??*/},
              account_id: (...),
              address_1: (...),
              address_2: (...),
              amount: 20.00,
              id: 1274}];

In this scenario, if there is no id within the data object, your map logic will not function correctly.

But let's imagine you want to retrieve data based on an external id. You could potentially try something like this:

let responseWithIdOutsideData = [{data: { /*is there an id here??*/},
                  account_id: "(...)",
                  address_1: "(...)",
                  address_2: "(...)",
                  amount: 10.00,
                  id: 1234},
                  {data: {/*is there an id here??*/},
                  account_id: "(...)",
                  address_1: "(...)",
                  address_2: "(...)",
                  amount: 20.00,
                  id: 1274}];
                  
let id = 1274;
let i = responseWithIdOutsideData.map(item => item.id).indexOf(id);
console.log(responseWithIdOutsideData[i].data);

Answer №2

It seems like your this.request_data may be causing confusion because you are trying to iterate over the response received from axios. You should extract the necessary values from the response and then find the index of a specific value.

cardClicked: function(id) {
  axios.get('api/get_vcard').then(response => {
    let i = response.data.map(item => item.data.id).indexOf(id);
        
    this.name_on_card = response.data[i].name_on_card;
    this.card_pan = response.data[i].card_pan;
    this.expiration = response.data[i].expiration;

  }).catch(error => console.log(error));
},

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 are the steps to clipping a canvas using CSS clip-path?

When it comes to clipping a canvas, there are multiple methods that can be used. One way is to create a path with getContext('2d') and set globalCompositeOperation. Another method involves using -webkit-clip-path or clip-path, though the latter m ...

"Android Webview's evaluateJavascript function is not returning the expected value

I am attempting to retrieve the username from a webview, but it is returning a null object. webView.settings.javaScriptEnabled = true webView.evaluateJavascript( "(function() { return document.getElementsByClassName('lgn-loginname') })() ...

Unable to conceal the scrollbar while keeping the div scrollable

I've been attempting to implement the techniques outlined in the guides on this site, but I'm encountering difficulty hiding the scroll bar while still maintaining scrolling functionality! My current approach involves setting the parent as relat ...

Guide to building a hierarchical data object with JavaScript

Prior This object consists of multiple rows: { "functions": [ { "package_id": "2", "module_id": "2", "data_id": "2" }, { "package_id": ...

What is the best library to utilize for uploading an Excel file in a React application?

As a beginner in JS and React, I have a simple question that I hope someone can help me with! I am trying to figure out how to upload an excel file using a form and then extract the data from the rows and columns. For example, I would like to calculate th ...

Refine JSON data by selecting only distinct key/value pairs

My JSON object has the following structure: var theSchools = { Bradley University: "bru", Knox College: "knox", Southern Illinois University Edwardsville: "siue",… } I am trying to find a way to retrieve the school name (key) based on the schoo ...

Quick question about utilizing Ajax with spans

<span name = "menu"> <!-- javascript here --> <!-- content loaded via ajax --> </span> <span name = "content"> <!-- content loaded via ajax --> <!-- updated by buttons from the menu--> </span> Seeking a ...

How to use getServerSideProps in Next.js

In my current scenario, I find myself within a folder in the pages directory, specifically in a file named [id].jsx. My goal is to make getServerSideProps return just the name of the page, for example /page/id123 should return id123. import Link from &a ...

Error: Laravel API request unsuccessful

After seeking advice in larachat and conducting thorough research on Google, I discovered that while similar inquiries have been made in the past, none of the suggested solutions seem to work for my particular case. My current challenge involves loading c ...

What other options are available for achieving the same functionality as FormData.delete() given its low level of support?

When building my website, I utilized the FormData.delete() method to exclude specific form fields before sending data to the server. However, I encountered a setback as this method is not supported on various browsers, including Safari. Therefore, I am in ...

Is Angular considered bad practice due to its reliance on singletons, despite its widespread use and popularity?

Angular relies on singletons for all its services, however using singletons is often frowned upon in the development community. Despite this controversy, I personally find Angular to be a valuable and effective tool. What am I overlooking? ...

Having trouble removing just one element from an array in Redux. Any suggestions on how to make it work properly?

I'm currently working on creating a dynamic algorithm for removing an item from an array. Reducer: import { LOAD_PAGES, REMOVE_PAGE } from "./dynamicMenuActions"; export const initialState = { pages: [] }; export const dynamicMenuReducer = (state ...

Vue.js v-for dynamically creates HTML blocks that capture the state of collapse with two-way data binding

I am currently working on capturing the click action state within an HTML v-for generated block for a collapsible function. I have set up a data table and it seems that the state is being captured correctly. However, I am facing an issue where the displa ...

Creating unique styles for components based on props in styled MUI: A comprehensive guide

One challenge I am facing is customizing the appearance of my component based on props, such as the "variant" prop using the 'styled' function. Here is an example code snippet: import { styled } from '@mui/material/styles'; const Remov ...

Tips for avoiding the default rendering of Nuxt 3 layout?

After reviewing the Nuxt 3 documentation and finding it lacking in explanation, I turned to the Nuxt 2 docs. According to them, the default layout should be replaced by a specific layout specified within the name property of the <nuxt-layout> compone ...

Encountering a ReferenceError while debugging MongoDB: The console object is undefined

Using a js file within mongodb, I implemented a code snippet containing a console.log expression for debugging purposes: use test; db.city.find().snapshot().forEach(function(city){ var Pos = city.Pos; if (Pos) { longLat = Pos.split(" ...

Which tools should I combine with Angular for developing both Android and iOS applications?

My primary focus has been on developing web apps using Angular, but now I am interested in creating native Android and iOS apps with Angular. I have heard about using Cordova, Capacitor, and NativeScript for this purpose, as alternatives to Ionic due to pe ...

Error message: "When namedPlaceHolder parameter is disabled, bind parameters must be in the form of an

Currently revamping my query due to a crucial API redesign. With the presence of a "file" as multipart/form-data, I found the need for a form handler since NextJS lacked one. After some workarounds with "multiparty", now I can successfully parse the incomi ...

Vue: Clearing arrays when selecting filters

I am encountering an issue with a form that contains multiple select dropdowns used to filter data on the page. As users make selections, the options within each dropdown decrease accordingly. However, I am struggling to find a way to reset these select m ...

Tips for updating parameters that are defined in a controller within a promise

Currently, I am developing a single page application using Angular and TypeScript. I am facing an issue with updating the parameter value (_isShowFirst) of the controller inside a promise function. It seems like nothing is recognized within the promise blo ...