![](/img/trans.png)
[英]Angular: How do I Rxjs filter by property through an array of objects?
[英]How do I filter through an Array with multiple objects in an Array and return lengths
我有一個包含多個對象的數組
var List = [
{
name: 'John',
city: 'Denver',
email: 'johnson@mail.com'
},
{
name: '',
city: 'Dever',
email: 'tom@mail.com'
},
{
name: 'Mark',
city: '',
email: '',
}
];
我以前使用過濾器返回填寫的姓名總數。
// returned filled out names
let total_name = List.filter((c: { name: any }) => !!c.name).length;
console.log(total_name); // returns 2
我想要完成的是過濾所有三個或更多對象並獲得項目的總長度,即 9 並獲得總長度為 5 的已填寫項目的總長度。
我對我接受的答案所做的更改。
isFilledLength(arr: any[], status: string) {
let y = 0;
arr.forEach((item) => {
for (const x in item) {
if (!!item[x] && status=='filled')
y++;
if(status=='full')
y++;
}
});
return y;
}
type Tuple = [number, number]
function totalAndNonEmptyProps(arr: Record<string, unknown>[]) {
const tuples: Tuple[] = arr.map((rec) => {
const keys = Object.keys(rec)
const nonEmptyKeys = keys.filter((key) => rec[key] != '')
return [keys.length, nonEmptyKeys.length]
})
return tuples.reduce(([a1, a2], [c1, c2]) => [a1 + c1, a2 + c2])
}
console.log(totalPropsAndNonEmptyProps(arr)) // [9, 6]
var List = [{ name: 'John', city: 'Denver', email: 'johnson@mail.com' }, { name: '', city: 'Dever', email: 'tom@mail.com' }, { name: 'Mark', city: '', email: '', } ]; function isFilledLength(arr, status) { let y = 0; arr.forEach((item) => { for (x in item) { if (!!item[x] && status=='filled') y++; if(status=='full') y++; } }); return y; } console.log('filled', isFilledLength(List, 'filled')); console.log('total filled', isFilledLength(List, 'full'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.