我的数组如下
createItem(): FormGroup {
return this.formBuilder.group({
staffMemberId: ['',],
name: ['',],
});
}
addItem(): void {
this.projectFundingItems = this.formProjectGeneralData.get('staffMembers') as FormArray;
this.projectFundingItems.push(this.createItem());
}
onTabChanged($event) {
let clickedIndex = $event.index;
let length = (<FormArray>this.formData.controls['staffMembers']).length;
if (clickedIndex === length) {
if ((<FormArray>this.formData.controls['staffMembers']).at(length - 1).dirty) {
this.addItem();
this.selectedTabIndex = clickedIndex - 1;
} else {
if (this.formData.staffMembers.length === clickedIndex) {
this.addItem();
}
this.selectedTabIndex = clickedIndex - 1;
}
}
}
我想针对特定的user_id过滤测试,例如,如果user_id = 4,我希望得到此结果
test_list = [
{
id: 1,
test_name: 'Test 1',
members: [
{
user_id: 3
},
{
user_id: 4
}
],
},
{
id: 2,
test_name: 'Test 2',
members: [
{
user_id: 4
},
{
user_id: 5
},
],
},
{
id: 3,
test_name: 'Test 2',
members: [
{
user_id: 8
},
{
user_id: 10
},
],
}
]
我已经尝试过了,但是只返回了成员
{
id: 1,
...
},
{
id: 2,
...
},
在这种情况下,有人可以帮我吗?
答案 0 :(得分:1)
检查.some
数组中的members
个对象是否具有您要查找的user_id
:
test_list = [{
id: 1,
test_name: 'Test 1',
members: [{
user_id: 3
},
{
user_id: 4
}
],
},
{
id: 2,
test_name: 'Test 2',
members: [{
user_id: 4
},
{
user_id: 5
},
],
},
{
id: 3,
test_name: 'Test 2',
members: [{
user_id: 8
}]
}
];
const filtered = test_list.filter(
({ members }) => members.some(
({ user_id }) => user_id === 4
)
);
console.log(filtered);
答案 1 :(得分:1)
您可以使用.reduce()
和.filter()
数组方法来获得所需的结果。
请检查以下工作代码段:
const arr = [{"id":1,"test_name":"Test 1","members":[{"user_id":3},{"user_id":4}]},{"id":2,"test_name":"Test 2","members":[{"user_id":4},{"user_id":5}]},{"id":3,"test_name":"Test 2","members":[{"user_id":8}]}];
const data = arr.reduce((r,{ members,...rest }) => {
let rec = members.filter(o => o.user_id === 4)
if(rec.length){
rest.members = rec;
r.push(rest);
}
return r;
},[]);
console.log(data);
答案 2 :(得分:0)
希望这行得通。
var members = item.members;
var filterById =members.filter((item1)=>{
return (item1.user_id===4)
});
return filterById.length > 0;
});
console.log(test_List_by_id)```