如何在TypeScript中合并具有共享ID的两个对象数组?

时间:2020-08-14 16:48:22

标签: javascript arrays angular typescript merge

我有两个共享ID的对象数组。如何将它们合并到单个阵列中,其中所有项目都已根据ID进行了合并?

我正在使用TypeScript和Angular。

const array0 = [
  {
    subject_id: "711",
    topics: [ "Test", "Test2" ]
  },
  {
    subject_id: "712",
   topics: [ "topic1", "Topic2" ]
  }
];

const array1 = [
  {
    subject_id: 711,
    subject_name: "Science"
  },
  {
    subject_id: 712,
    subject_name: "Maths"
  }
];

I want the merged result to be:

const result = [
  {
    subject_id: "711",
    subjectName: "Science",
    topics: [ "Test", "Test2" ]
  },
  {
    subject_id: "712",
    subjectName: "Maths",
    topics: [ "topic1", "Topic2" ]
  }
];

2 个答案:

答案 0 :(得分:2)

我认为您可以使用类似这样的东西:

selectedSubjects = [
                     { subject_id: 711, topics: ["Test", "Test2"] },
                     { subject_id: 712, topics: ["topic1", "Topic2"] }
                   ]

theOtherSubjects = [
                     {subject_id: 711, subject_name: "Science"},
                     {subject_id: 712, subject_name: "Maths"}
                   ] // fixed the ids as I supposed the should be the same, otherwise it makes no sense with the provided data

let mergedSubjects = selectedSubjects.map(subject => {
    let otherSubject = theOtherSubjecs.find(element => element.subject_id === subject.subject_id)
    return { ...subject, ...otherSubject }
})

答案 1 :(得分:1)

一种方法:

selectedSubjects = [
    { subject_id: "711", topics: ["Test", "Test2"] },
    { subject_id: "712", topics: ["topic1", "Topic2"] }
  ];
  anotherArray = [
    { subject_id: 711, subject_name: "Science" },
    { subject_id: 712, subject_name: "Maths" }
  ];

  finalArray = [];

  createFinalArray() {
    this.selectedSubjects.map(s1 => {
      this.finalArray.push({
        subject_id: s1.subject_id,
        subject_name: this.anotherArray.find(s2 => s2.subject_id.toString()===s1.subject_id).subject_id,
        topics: s1.topics
      });
    })
  }