[英]Need to merge two objects together that each have an array to the matching IDs
我有兩個對象,它們的數組均為“ allSessionsParts”和“ allSessions”。
我試圖讓allSessions-> SessionsParts僅在allSession.ID與allSessionsParts.SessionID匹配時才具有allSessionsParts
到目前為止,這是我的嘗試。
const res = allSessions.map(function(sess, i) {
if (sess.ID === allSessionsParts.SessionID) {
return {
sess,
parts: allSessionsParts
};
}
});
更新
解
completeSessions.map(sess => {
if(sess.SessionParts==null){
sess.SessionParts=[]
}
parts.forEach(part => {
if(part.SessionID === sess.ID){
sess.SessionParts.push(part)
}
});
})
您需要遍歷數組allSessions
,對於每個會話,都需要遍歷數組allSessionParts
來檢查匹配的SessionId
是否存在
const validSessions = allSessions.filter(session =>
allSessionParts.some(sessionPart => session.ID === sessionPart.SessionId
);
Iterate over both arrays and compare array1.id === array2.sessionId,
if true push {...object1, ...object2} in new array.
這是可行的解決方案。
var array1 = [ { id:101, firstName: "rama" }, { id:102, firstName: "shyam" }, { id:103, firstName: "jai" } ]; var array2 = [ { sessionId:101, lastName: "singh" }, { sessionId:102, lastName: "kumar" }, { sessionId:105, lastName: "jakhar" } ]; let array3 = []; array1.forEach(item => { array2.forEach(item2 => { if(item.id === item2.sessionId){ array3.push({...item, ...item2}) } }) }) console.log(array3);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.