繁体   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