簡體   English   中英

檢查值是否在數組中並返回 true 或 false angular 6+

[英]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#somestring#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循環外部鏈接。 然后使用someincludes來檢查角色是否存在。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM