[英]Check if value is in array and return true or false angular 6+
我有一些這樣的數組
roles = ['AnyRulesGo@admin', 'NoRules@admin', 'HowYesNo@history', 'MamaMia@survey'];
我有一些這樣的對象
externalLinks = [
{
link: '#',
icon: 'Icon',
translation: 'Home',
role: '@history',
active: false,
visible: false
},
{
link: '#',
icon: 'Task',
translation: 'Tasks',
role: '@task',
active: false,
visible: false
},
{
link: '#',
icon: 'Files',
translation: 'Files',
role: '@admin',
active: true,
visible: false
}
];
我需要一些功能來檢查確實在externaLinks價值作用,在陣列的角色存在,並更新該值在externalLinks可見從假到真
我沒有更多的代碼,因為我什至不知道從哪里開始,任何幫助都會很棒,謝謝
問題之一是我完成了僅從@ 開始的角色名稱,這意味着我需要剪切該字符串,然后進行比較?
我試過這個功能,但沒有運氣
function objectsAreSame(x, y) {
var objectsAreSame = true;
for(var propertyName in x) {
if(x[propertyName] !== y[propertyName]) {
objectsAreSame = false;
break;
}
}
return objectsAreSame;
}
您可以使用array#forEach
遍歷externalLinks
每個對象。 然后使用array#some
和string#incldues
檢查roles
數組中的roles
並更新visible
鍵的值。
let roles = ['AnyRulesGo@admin', 'NoRules@admin', 'HowYesNo@history', 'MamaMia@survey'], externalLinks = [ { link: '#', icon: 'Icon', translation: 'Home', role: '@history', active: false, visible: false }, { link: '#', icon: 'Task', translation: 'Tasks', role: '@task', active: false, visible: false }, { link: '#', icon: 'Files', translation: 'Files', role: '@admin', active: true, visible: false } ]; externalLinks.forEach(o => { o.visible = false; if(roles.some(r => r.includes(o.role))) o.visible = true; }); console.log(externalLinks);
您可以使用forEach
循環外部鏈接。 然后使用some
和includes
來檢查角色是否存在。
roles = ['AnyRulesGo@admin', 'NoRules@admin', 'HowYesNo@history', 'MamaMia@survey'];
externalLinks.forEach((extLink) => {
if(roles.some(role => role.includes(extLink.role))){
extLink.visible = true;
}
})
做兩個循環:
//Make all false
externalLinks.forEach(x=>x.visible=false);
//for each role, filter by role and forEach value filtered, make visible
role.forEach(role=>{
let busc="@"+role.split('@')[1]
externalLinks.filter(x=>x.role==busc)
.forEach(xfilter=>xfilter.visible=true)
})
//If only want a role "roleSearch"
let busc="@"+roleSearch.split('@')[1]
externalLinks.filter(x=>x.role==busc)
.forEach(xfilter=>xfilter.visible=true)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.