【问题标题】:How to filter array of objects and check if more than one object inside the array has the same property value in Javascript?如何过滤对象数组并检查数组中是否有多个对象在Javascript中具有相同的属性值?
【发布时间】:2020-11-27 21:37:28
【问题描述】:

如何过滤对象数组并检查数组中是否有多个对象具有相同的属性值计划在Javascript中的“企业”。

    this.accounts
              .filter(
                item => item.plan === 'enterprise'
              )
              // then how can I check if there is more than one object
              // containing above enterprise value? if so then return some message.
          }

如何继续进行上述过滤以达到结果?

【问题讨论】:

  • .filter() 方法遍历数组的所有元素。
  • 你已经检查过了,它将累积所有具有指定属性的对象
  • @EugenSunic 我需要检查是否有多个对象使用该过滤器,然后返回一些消息
  • 检查返回数组的长度,如果 > 1 发出警报

标签: javascript arrays ecmascript-6 javascript-objects ecmascript-5


【解决方案1】:

执行过滤器后,您可以只计算filter 方法结果中的项目数。这将告诉您有多少个企业计划帐户

var accounts = [
 {id: 1, name: "Account 1", plan: "basic"},
 {id: 2, name: "Account 2", plan: "medium"},
 {id: 3, name: "Account 3", plan: "enterprise"},
 {id: 4, name: "Account 4", plan: "medium"},
 {id: 5, name: "Account 5", plan: "enterprise"}
]


var enterpriseAccounts = accounts.filter(item => item.plan === "enterprise");

if(enterpriseAccounts.length > 1 ) {
  console.log('There are more than one enterprise account');
} else {
 console.log('There are 0 or 1 enterprise account');
}

【讨论】:

    【解决方案2】:

    只需过滤,然后得到长度。

    accounts = [{plan: 'test'}, {plan: 'extra'}, {plan: 'enterprise'}, {plan: 'basic'}, {plan: 'enterprise'}];
    let length = accounts.filter(item => item.plan === 'enterprise').length;
    
    if (length>1) console.log('enterprise more than once: ' + length);

    【讨论】:

      【解决方案3】:

      您可以获取数组的长度,然后检查它是否大于一,从而打印一条消息

       const elmCount = this.accounts
         .filter(
           item => item.plan === 'enterprise'
         ).length
      
       if (elmCount > 1) {
         console.log('print message')
       }
      

      【讨论】:

        猜你喜欢
        • 2023-03-26
        • 2020-12-27
        • 2020-06-30
        • 1970-01-01
        • 2013-10-14
        • 1970-01-01
        • 2021-08-19
        • 2014-01-01
        相关资源
        最近更新 更多