在 JavaScript 中,你可以使用對象合併(Object merging)來模擬數據庫的左聯接操作。左聯接操作會將兩個對象的特定屬性進行合併,類似於 SQL 中的 LEFT JOIN 操作。
假設你有兩個對象,每個對象代表一個表:
const table1 = [
{ id: 1, age: 30 },
{ id: 3, age: 25 },
];
const table2 = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Charlie" },
];
你可以通過以下代碼實現類似數據庫左聯接的對象合併:
function leftJoin(table1, table2, key) {
const result = [];
table1.forEach((row1) => {
const matchingRows = table2.filter((row2) => row1[key] === row2[key]);
if (matchingRows.length > 0) {
matchingRows.forEach((matchingRow) => {
result.push({ ...row1, ...matchingRow });
});
} else {
result.push({ ...row1 });
}
});
return result;
}
const mergedTable = leftJoin(table1, table2, "id");
console.log(mergedTable);
打印結果:
[
{ id: 1, age: 30, name: "Alice" },
{ id: 3, age: 25, name: "Charlie" },
];
這段代碼會將 table1
和 table2
進行左聯接操作,以 id
屬性爲鍵進行合併。合併後的結果存儲在 mergedTable
數組中,並輸出到控制檯。
這裏的 leftJoin
函數接受三個參數:兩個表格的數組以及用來匹配的鍵名。它遍歷第一個表格的每一行,並在第二個表格中查找匹配的行。如果找到匹配的行,則將兩行合併爲一個新的對象,然後將其添加到結果數組中。如果沒有找到匹配的行,則僅將第一個表格中的行添加到結果數組中。