繁体   English   中英

JavaScript 从 Object Id 的选定数组中获取索引

[英]JavaScript Get Indexes based from the Selected Array of Object Id

今天,我试图根据我拥有的选定数据 id 获取 javascript 索引列表。

我正在遵循https://buefy.org/documentation/table/#checkable中的本指南,它需要这样的内容: checkedRows: [data[1], data[3]]能够检查桌子。

我需要做的是根据我的 web API 响应检查表格。

我有这个示例响应数据。

response.data.checkedRows // value is [{id: 1234}, {id: 83412}]

我有表格中的样本数据。

const data = [{
    id: 1234,
    name: 'Jojo'
},{
    id: 43221,
    name: 'Jeff'
},{
    id: 83412,
    name: 'Kacey'
}]

所以基本上,我需要动态地拥有一些东西,比如: checkedRows: [data[0], data[2]]因为它匹配来自response.data.checkedRows的数据

到目前为止,我尝试使用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]]
         }
     });
});

我被困在这里,因为我不确定如何从响应中获取与所选 checkRows 匹配的索引。 有什么帮助吗?

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);

如果元素很多,可以使用一组 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM