首页 > 解决方案 > JavaScript 根据选定的对象 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 匹配的索引。有什么帮助吗?

标签: javascriptarrays

解决方案


映射响应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);


推荐阅读