根据公共 id 合并两个数组

Merge two array based on common id

我有这样的功能,我要将其传递给 classid

  selectedSubjects;
  classnamewithid;
  subjectNameByID;

  selectClass(selectedClass) {
          

    this.selectedSubjects = this.topicWithClassSubjectList.filter(
      (topic) => topic.class_id === selectedClass
    ); // to filter out class with same id
   

    const groups = this.selectedSubjects.reduce((acc, cur) => {
      (acc[cur.subject_id] = acc[cur.subject_id] || []).push(cur.topic_name);
      return acc;
    }, {}); // to group the array according to subject
   
// checkpoint#1
    this.selectedSubjects = Object.keys(groups).map((key) => ({
      subject_id: key,
      topics: groups[key],
    }));

  }

我的class列表数组是这样的

{class_id: 1871, class_name: "1st"},
{class_id: 1872, class_name: "2nd"},

checkpoint#1 之后的 selectedSubjects 的最终数组是

[{"subject_id":"551","topics":["Evolution"]},{"subject_id":"711","topics":["Vector"]}]

我想要在 selectedSubjects 数组中为每个 subject_id 关联一个 subjectName。我有一个 subjectId 数组,SubjectName 为:

{class_id: 2711, subject_id: 551, subject_name: "Biology"}

我希望 selectedSubjects 数组看起来像这样

[{"subject_id":"551", "subject_name":"生物学", 主题":["进化论"]},{"subject_id": "711","subject_name":"science","topics":["Vector"]}]

如果没有一个最小的例子,我不完全确定你的数据是什么样的,但根据描述,这样的东西应该有效。

const subjectsToTopics = [{
  subject_id: 551,
  topics: ["Evolution"]
}, {
  subject_id: 711,
  topics: ["Vector"]
}];
const classList = [{
    class_id: 1871,
    class_name: "1st"
  },
  {
    class_id: 1872,
    class_name: "2nd"
  },
];
const topicWithClassSubjectList = [{
    class_id: 1871,
    subject_id: 551,
    subject_name: "Biology"
  },
  {
    class_id: 1872,
    subject_id: 551,
    subject_name: "Biology"
  }
];

function selectClass(selectedClass) {
  const classnamewithid = classList.find(
    (classes) => classes.class_id === selectedClass
  ); // to get the class name and class ID of selected class

  if (classnamewithid === null) {
    throw Error(`Class with id ${selectedClass} not found`);
  }

  const selectedSubjects = topicWithClassSubjectList.filter(
    (topic) => topic.class_id === selectedClass
  ); // to filter out class with same id


  return selectedSubjects.map((subject) => ({
    subject_id: subject.subject_id,
    subject_name: subject.subject_name,
    topics: subjectsToTopics
      .filter((entry) => entry.subject_id == subject.subject_id)
      .map((entry) => entry.topics)
      .flat()
  }));
}

console.log(selectClass(1871));
console.log(selectClass(1872));

请注意,您没有在任何地方使用 classnamewithid,因此您可以删除它。