arrays - Typescript - Check values in one array are present in another
问题描述
I have the following array. I am using this array to dynamically produce checkboxes on my UI. This is being used to save user config as to what they will be able to see in a nav menu.
accessLevels: any = [
{
description: "Properties",
type: '1',
selected: false
},
{
description: "Equipment",
type: '2',
selected: false
},
{
description: "Jobs",
type: '3',
selected: false
},
{
description: "Calender",
type: '4',
selected: false
}
]
I am making a call to an API which returns me an array of the users config. So what I will get is an array of the pages and their type like this:
{
description: "Equipment",
type: '2'
},
{
description: "Jobs",
type: '3'
}
In the array returned from the API I am just getting the values that should appear checked on the check boxes so what I want to do is loop through the returned array and check if any of the types match any types in the checkbox array if they do I want to set 'selected' to true. Thus checking the checkbox.
Here is what I have so far:
async loadLandlordConfig(key: string) {
const result = await this.userService.loadLandlordConfig(key);
//let accessLevels = [];
this.selectedApiValues = result[0].accessLevels;
this.selectedApiValues.forEach((selectedValue)=> {
});
}
Im not sure how to cross check the values and then change selected to true.
Hope I have made everything clear enough. Any questions please ask. All help appreciated.
解决方案
You can achieve what you want with the following simple example :
let accessLevels = [
{
description: "Properties",
type: '1',
selected: false
},
{
description: "Equipment",
type: '2',
selected: false
},
{
description: "Jobs",
type: '3',
selected: false
},
{
description: "Calender",
value: '4',
selected: false
}
]
let api = [
{
description: "Equipment",
type: '2'
},
{
description: "Jobs",
value: '3'
}
];
for(var i = 0; i < accessLevels.length; i++) {
accessLevels[i].selected = api.find(e => e.description === accessLevels[i].description) ? true : false;
}
console.log(accessLevels);
推荐阅读
- javascript - 使用模板使用的所有 CSS 规则生成一个内置的 angular index.html 页面?
- excel - 通过“结果”在 VBA 中查找
- c++ - 为什么类内部不允许初始化静态成员变量,但允许初始化 const 静态成员?
- html - 本地 HREF="" 标记未将一个页面链接到另一个页面
- android - 我可以使用 Facebook API 在群组上发帖吗?
- sql - 复制数据表到数据库 asp VB
- javascript - 如何访问使用 $.getScript 运行的脚本中的函数或变量
- kubernetes - 如何将 chrome 调试器连接到 kubernetes pod
- php - Foreach 循环未按预期工作
- gensim - 如何使用 gensim 的 LDA 从查询中进行文本检索?