如何过滤对象数组并检查数组中是否有多个对象在 Javascript 中具有相同的 属性 值?
How to filter array of objects and check if more than one object inside the array has the same property value in Javascript?
如何筛选对象数组并检查数组中是否有多个对象在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')
}
过滤然后得到长度
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);
执行过滤器后,您可以计算 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');
}
如何筛选对象数组并检查数组中是否有多个对象在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')
}
过滤然后得到长度
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);
执行过滤器后,您可以计算 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');
}