如何在 TypeScript 中合并两个具有共享 ID 的对象数组? [英] How do I merge two arrays of Objects with a shared ID in TypeScript?
本文介绍了如何在 TypeScript 中合并两个具有共享 ID 的对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个共享一个 ID 的对象数组.如何将它们合并到一个 Array 中,其中所有项目都已根据 ID 合并?
I have two Arrays of Objects, that share an ID. How do I merge them into a single Array, where all items have been merged based on the ID?
我使用的是 TypeScript 和 Angular.
I'm using TypeScript and 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" ]
}
];
推荐答案
我想你可以这样使用:
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 }
})
这篇关于如何在 TypeScript 中合并两个具有共享 ID 的对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文