javascript - 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 匹配的索引。有什么帮助吗?
解决方案
映射响应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);
推荐阅读
- reactjs - 构建后 React web 无法正常工作(相关 axios api)
- c# - ASP.Net MVC 无法编辑用户,因为用户类中的 [比较(密码)]
- python - 如何通过匹配字典值向数据框添加二级列标题/索引?
- java - 深拷贝中 java.util.Date 的行为
- vuejs2 - Rails API 响应请求,但 axios 未检索数据
- asp.net - 托管一个无需图形界面即可上传和下载文件的 Web 应用程序
- python - Pyarrow Table.from_pandas 更改提供的模式
- reactjs - 全日历不工作,全日历未定义错误
- java - Java 线程运行顺序
- python - 没有出现属性错误,属性似乎在那里?