【问题标题】:How do I remove an row from an array based on specific condition in Javascript如何根据Javascript中的特定条件从数组中删除一行
【发布时间】:2020-02-22 13:11:14
【问题描述】:

我有一个名为 userList 的数组,并通过循环将一些数据推入其中来填充它... 像这样

userList.push({
  userProfileID : dataEntry.UserProfileID ,
  isAgent       : dataEntry.isAgent       ,
  firstName     : dataEntry.firstName     ,
  roleNames     : dataEntry.roleNames
})

输出会是这样,还有 100 多条记录

0: Object {userProfileID: "68670", isAgent: false, firstName: "ARSDEO", roleNames:"Deo Role"}
1: Object {userProfileID: "68672", isAgent: false, firstName: "ARSBM101", roleNames:"BM Role"}
2:.......
3:.......

这里我想删除 userList 数组中 roleNames = 'BM role' 的条目

我试过这个:

userList = userList.filter(item => userList.roleNames == 'BM Role');

但我在数组中没有记录。 请指教...

【问题讨论】:

  • filter 不会删除任何内容,它会创建一个新数组。要删除元素,请使用 splice

标签: javascript arrays filtering


【解决方案1】:

差不多了。

您想检查 item 上的属性 rolesNames 是否不等于“BM 角色”(即您想过滤掉那些) p>

const newList = userList.filter(item => item.roleNames !== 'BM Role');

注意:filter 与其他函数式数组方法 mapreduce 一样,不会改变数组,它会返回一个 new 数组,其中仅包含符合条件的元素在回调中。

【讨论】:

    【解决方案2】:

    尝试检查角色名称isn't equal 是否为'Bm Role'

    userList = userList.filter((user) => {
        return user.roleNames !== 'BM role';
    })
    

    顺便说一句 filter() 方法创建原始数组的副本。

    但是如果你想直接从原始数组中删除,我建议你使用splice()方法:

    for(let i = 0; i < userList.length; i++){ 
       if (userList[i].roleNames === 'BM Role') {
          userList.splice(i, 1); 
          i--;
       }
    }
    

    【讨论】:

      【解决方案3】:

      如果问题是关于从 userList 中删除元素:

      var userList = 
      [ { userProfileID: '68670', isAgent: false, firstName: 'ARSDEO', roleNames: 'Deo Role' } 
      , { userProfileID: '68672', isAgent: false, firstName: 'aaaaaa', roleNames: 'aaa Role' } 
      , { userProfileID: '68674', isAgent: false, firstName: 'bbbbbb', roleNames: 'BM Role'  } 
      , { userProfileID: '68676', isAgent: false, firstName: 'cccccc', roleNames: 'BM Role'  } 
      , { userProfileID: '68678', isAgent: false, firstName: 'dddddd', roleNames: 'bbb Role' } 
      ] 
        
      
      for (let i=userList.length;i--;)  // start from end to zero
      {
        if (userList[i].roleNames==='BM Role') { userList.splice(i, 1) }
      }
      
      for (let elm of userList ) { console.log( JSON.stringify(elm) )  }

      【讨论】:

        【解决方案4】:

        您应该使用item.roleNames 而不是userList.roleNames,因为roleNames 是数组中特定对象/项的一部分,而不是数组本身。 此外,您可能应该使用item.roleNames != 'BM Role',因为过滤器返回一个包含匹配项的数组,并且您想要删除匹配项。

        【讨论】:

          【解决方案5】:

          您的过滤器不正确:

          userList = userList.filter(item => item.roleNames != 'BM Role');
          

          item 变量是您要检查的对象。在每次过滤器调用时,都会将一个新项目传递给函数,这就是正在评估的内容

          【讨论】:

          • OP 想要一个包含 BM 角色的项目的过滤列表。
          猜你喜欢
          • 1970-01-01
          • 2018-05-28
          • 1970-01-01
          • 2019-09-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多