[英]JavaScript Get Indexes based from the Selected Array of Object Id
Today, I'm trying to get the list of javascript index based from the selected data id that I have.今天,我试图根据我拥有的选定数据 id 获取 javascript 索引列表。
I'm following this guide from https://buefy.org/documentation/table/#checkable where it needs something like this: checkedRows: [data[1], data[3]]
to able to check the specific row in the table.我正在遵循https://buefy.org/documentation/table/#checkable中的本指南,它需要这样的内容: checkedRows: [data[1], data[3]]
能够检查桌子。
What I need to do is to check the table based from my web API response.我需要做的是根据我的 web API 响应检查表格。
I have this sample response data.我有这个示例响应数据。
response.data.checkedRows // value is [{id: 1234}, {id: 83412}]
and I have the sample data from the table.我有表格中的样本数据。
const data = [{
id: 1234,
name: 'Jojo'
},{
id: 43221,
name: 'Jeff'
},{
id: 83412,
name: 'Kacey'
}]
So basically, I need to have something, dynamically, like this: checkedRows: [data[0], data[2]]
because it matches the data from the response.data.checkedRows
所以基本上,我需要动态地拥有一些东西,比如: checkedRows: [data[0], data[2]]
因为它匹配来自response.data.checkedRows
的数据
So far, I tried using forEach
到目前为止,我尝试使用forEach
let selectedIndex = [];
response.data.checkedRows.forEach((d) => {
this.data.forEach((e) => {
if (d.id=== e.id) {
// need the result to be dynamic depending on the response.data.checkedRows
this.checkedRows = [data[0], data[2]]
}
});
});
I'm stuck here because I'm not sure how can I get the index that matches the selected checkedRows from response.我被困在这里,因为我不确定如何从响应中获取与所选 checkRows 匹配的索引。 Any help?有什么帮助吗?
Map the response checkedRows
, and in the callback, .find
the matching object in the array: Map 响应checkedRows
,并在回调中,在数组中找到匹配的.find
:
const checkedRows = [{id: 1234}, {id: 83412}]; const data = [{ id: 1234, name: 'Jojo' },{ id: 43221, name: 'Jeff' },{ id: 83412, name: 'Kacey' }]; const objs = checkedRows.map(({ id }) => ( data.find(obj => obj.id === id) )); console.log(objs);
If there are a lot of elements, you can use a Set of the IDs to find instead to decrease the computational complexity:如果元素很多,可以使用一组 ID 来查找,以降低计算复杂度:
const checkedRows = [{id: 1234}, {id: 83412}]; const data = [{ id: 1234, name: 'Jojo' },{ id: 43221, name: 'Jeff' },{ id: 83412, name: 'Kacey' }]; const ids = new Set(checkedRows.map(({ id }) => id)); const objs = data.filter(obj => ids.has(obj.id)); console.log(objs);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.