如何用父数组对象的子ID数组过滤子对象数组?
Fixing Your Parent-Child Data Matching Function
Let's walk through fixing your function to correctly fetch the child records linked to a specific parent. Your current code has two critical issues that are preventing it from working as expected:
Key Issues in the Original Code
- Incorrect property reference: You're accessing
singleParentRecord[0].books, but the requirement states the parent object's child ID array is stored in thechildfield, notbooks. Additionally, directly grabbing[0]from the filter result is risky—if no parent matches theParentId, this will throw an error when trying to access.books. - Broken child filtering logic: You're comparing
child.id === parentsChildIds, butparentsChildIdsis an array of IDs. A single ID can never be strictly equal to an array, so this filter will always return an empty set.
Corrected Code
function currentChildrenIds(ParentId, parentData, childData) { // Find the parent record matching the given ParentId (returns undefined if not found) const parentRecord = parentData.find(parent => parent.id === ParentId); // If no parent found, return empty array to avoid errors if (!parentRecord) { return []; } // Get the array of child IDs from the parent's `child` field const parentChildIds = parentRecord.child; // Filter childData to include only records whose ID is in parentChildIds const linkedChildRecords = childData.filter(child => parentChildIds.includes(child.id)); return linkedChildRecords; }
What Changed & Why
- Used
find()instead offilter():find()returns the first matching parent object directly (instead of an array), which is more efficient since we only expect one parent with the given ID. It also avoids the need to access[0]. - Added a check for missing parent record: If no parent matches the provided
ParentId, the function safely returns an empty array instead of throwing a "cannot read property of undefined" error. - Fixed the property name: Changed
bookstochildto align with your requirement that the parent's child ID array is stored in thechildfield. - Corrected the filter logic: Used
Array.includes()to check if a child's ID exists in the parent's child ID array—this is the correct way to match individual IDs against an array of values.
Example Test Case
Using your sample data:
- Parent data:
[{ id: 'parent1', child: [1, 2] }, { id: 'parent2', child: [3] }] - Child data:
[{ id: 1, name: 'Child 1' }, { id: 2, name: 'Child 2' }, { id: 3, name: 'Child 3' }]
Calling currentChildrenIds('parent1', parentData, childData) will return:
[{ id: 1, name: 'Child 1' }, { id: 2, name: 'Child 2' }]
Which matches your expected output.
内容的提问来源于stack exchange,提问作者Paul A
相关产品推荐
相关产品推荐

