You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用父数组对象的子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 the child field, not books. Additionally, directly grabbing [0] from the filter result is risky—if no parent matches the ParentId, this will throw an error when trying to access .books.
  • Broken child filtering logic: You're comparing child.id === parentsChildIds, but parentsChildIds is 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

  1. Used find() instead of filter(): 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].
  2. 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.
  3. Fixed the property name: Changed books to child to align with your requirement that the parent's child ID array is stored in the child field.
  4. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 08:07:44