JavaScript 实现类似SQL 左联接式的对象数组合并

JavaScript 实现类似 SQL 左联接式的对象数组合并

在 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" },
];

这段代码会将 table1table2 进行左联接操作,以 id 属性为键进行合并。合并后的结果存储在 mergedTable 数组中,并输出到控制台。

这里的 leftJoin 函数接受三个参数:两个表格的数组以及用来匹配的键名。它遍历第一个表格的每一行,并在第二个表格中查找匹配的行。如果找到匹配的行,则将两行合并为一个新的对象,然后将其添加到结果数组中。如果没有找到匹配的行,则仅将第一个表格中的行添加到结果数组中。

posted @ 2024-02-06 15:45  飞仔FeiZai  阅读(15)  评论(0编辑  收藏  举报