javascript - 获取对象的 indexOf
问题描述
我有一个看起来像这样的数组
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
我正在进行 axios 调用以获取单击的特定项目的数据并以模式显示它,所以我有这个
<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));
},
}
当我单击按钮时,它不会提取数据
但是当我为其中一个条目尝试此操作时,它可以工作并提取数据
this.name_on_card = response.data[i].name_on_card;
我如何正确映射它以获取单击项目的索引并显示数据?
解决方案
Ciao,很遗憾你没有显示response.data
. 无论如何假设response.data
包含一个id,你map
是正确的。我做了一个例子:
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) // return 1 ok!
但我不知道是否responseWithIdInData
像您的数据形状。事实上,您的代码似乎更像是您的响应是这样的:
let responseWithIdOutsideData = [{data: { /*there is an id here??*/},
account_id: (...),
address_1: (...),
address_2: (...),
amount: 10.00,
id: 1234},
{data: {/*there is an id here??*/},
account_id: (...),
address_1: (...),
address_2: (...),
amount: 20.00,
id: 1274}];
在第二种情况下,我不知道,因为如果里面没有 id data
,你的map
就行不通了。
但是让我们假设您想data
使用外部 id。你可以尝试做这样的事情:
let responseWithIdOutsideData = [{data: { /*there is an id here??*/},
account_id: "(...)",
address_1: "(...)",
address_2: "(...)",
amount: 10.00,
id: 1234},
{data: {/*there is 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);
推荐阅读
- tensorflow - 如何在tensorflow中实现自定义损失函数并进行梯度反向传播
- javascript - jQuery 如果每个 li == 0 内的每个输入值
- php - 如何使用源和目的地时间计算旅行时间?
- mysql - MySQL 为 JOINed 表中的每一行提供结果
- ios - Swift:从 AppDelegate 中的 UNTextInputNotificationAction 获取内容
- java - 尝试使用 TestNG 和 WebDriverManager 运行测试时出错
- sql - 循环通过bulkcolumn SQL Server获取静态字符串之间的值
- ios - Swift 4 无法读取数据,因为它的格式不正确
- r - 将文本附加到 Excel 文件
- python-3.x - 在控制台中写作有效,脚本无效