gpt4 book ai didi

javascript - 如何通过其子数组对象属性计算父数组的项数

转载 作者:行者123 更新时间:2023-11-30 07:54:43 25 4
gpt4 key购买 nike

假设我有一组人员,其中有很多办公室。

var personnel = [
{
id: 1,
name: 'John Doe',
offices: [
{
id: 1,
name: 'Office 1',
isAssigned: false
},
{
id: 2,
name: 'Office 2',
isAssigned: true
},
{
id: 3,
name: 'Office 3',
isAssigned: false
}
]
},{
id: 2,
name: 'Jerry Smith',
offices: [
{
id: 2,
name: 'Office 2',
isAssigned: true,
},
{
id: 3,
name: 'Office 3',
isAssigned: false,
}
]
}
]

我如何获得分配到特定办公室的人员数量?或者在 office 2 中分配了多少?结果:2

最佳答案

这里是解构参数的版本:

personnel.filter( ({offices}) => 
offices.some( ({name, isAssigned}) => isAssigned && name === office)
).length

function countInOffice(personnel, office) {
return personnel.filter( ({offices}) =>
offices.some( ({name, isAssigned}) => isAssigned && name === office)
).length
}

var personnel = [
{
id: 1,
name: 'John Doe',
offices: [
{
id: 1,
name: 'Office 1',
isAssigned: false
},
{
id: 2,
name: 'Office 2',
isAssigned: true
},
{
id: 3,
name: 'Office 3',
isAssigned: false
}
]
},{
id: 2,
name: 'Jerry Smith',
offices: [
{
id: 2,
name: 'Office 2',
isAssigned: true,
},
{
id: 3,
name: 'Office 3',
isAssigned: false,
}
]
}
];

var count = countInOffice(personnel, 'Office 2');

console.log(count);

关于javascript - 如何通过其子数组对象属性计算父数组的项数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43040122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com