[英]how to get objects with the same property and has the max value in array - Javascript
[英]How to filter array of objects and check if more than one object inside the array has the same property value in Javascript?
如何过滤对象数组并检查数组中是否有多个 object 在 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.
}
如何继续进行上述过滤以达到结果?
您可以获取数组的长度,然后检查它是否大于一,因此打印一条消息
const elmCount = this.accounts
.filter(
item => item.plan === 'enterprise'
).length
if (elmCount > 1) {
console.log('print message')
}
执行过滤器后,您可以只计算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'); }
只需过滤然后获取长度。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.