【问题标题】:Loop through JS Object and function on each item循环遍历每个项目上的 JS 对象和函数
【发布时间】:2018-06-26 06:57:09
【问题描述】:

我一定是在想这个问题的解决方案,但似乎无法做到这一点。

我有一个数组object,如下所示:

[ 
  {  ItemID: 1,  Path: '/Admin',     Name: 'Admin'   },
  {  ItemID: 2,  Path: '/Product',   Name: 'Product' },
  {  ItemID: 1,  Path: '/Reports',   Name: 'Reports' } 
]

我想映射每个项目,并且我需要为每个项目运行一个函数,该函数将返回它们是否具有访问权限。即布尔值(是/否)。

到目前为止,我有这样的事情:

const newData = data.map((curr, val , arr) => {

    if (checkAccess(username, curr.Name )) {  //checkAccess returns true or false
        return { ...current };
    }
});

我只想退回他们有权访问的那些。

所以假设用户无法访问Admin,最终的对象应该是:

[ 
  {  ItemID: 2,  Path: '/Product',   Name: 'Product' },
  {  ItemID: 1,  Path: '/Reports',   Name: 'Reports' } 
]

编辑:

问题还在于该函数没有返回真/假

function checkInGroup(username, name) {
    let inGroup = "";
    ad.isUserMemberOf(username, name, function(err, isMember) {
        if (err) {
            return res.json("Error ", err);
        }
        inGroup = isMember; //this part returns true
    });
    return inGroup; //this seems to return empty string
}

【问题讨论】:

标签: javascript function ecmascript-6


【解决方案1】:

尝试使用filter,因为它会创建一个包含所有满足条件的元素的新数组:

const res = data.filter(obj => obj.Path !== '/Admin');
console.log(res);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 2019-08-08
    • 1970-01-01
    • 2015-09-19
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多