簡體   English   中英

如何使用屬性作為主鍵左連接 arrays 的兩個 javascript 對象?

[英]How can I left join two javascript objects of arrays using properties as primary keys?

我有兩個對象代表兩個 SQL 表。 這里有兩個簡化版本(它們都可能有更多的屬性):

const object1 = {
  key1: [  1,   1,   1,   2,   2,  3 ],
  key2: ['a', 'b', 'c', 'a', 'c', 'b'],
  prop3: ['A', 'B', 'C', 'D', 'E', 'F'],
}
const object2 = {
  key1: [  1,   1,   2],
  key2: ['a', 'c', 'a'],
  prop4: [10, 20, 30],
}

我想對key1key2執行左連接。 就像是:

select * 
from object1 o1
left join object2 o2 on o1.key1 = o2.key1 and o1.key2 = o2.key2

或者在 JS 中:

const object12 = {
  key1: [  1,   1,   1,   2,   2,  3 ],
  key2: ['a', 'b', 'c', 'a', 'c', 'b'],
  prop3: ['A', 'B', 'C', 'D', 'E', 'F'],
  prop4: [10, null, 20, 30, null, null],
}

在 JS 中執行此操作的便捷方法是什么? (允許使用 lodash)

const table = (entries, keys) => {
  const toData = () => Object.fromEntries(keys.map(k => [k, entries.map(it => it[k] ?? null)]));
  const join = (other, on) => table(
    entries.map(entry => ({ ...entry, ...(other.entries.find(other => on(entry, other)) ?? {}) })),
    [...keys, ...other.keys]
  );
  return { entries, keys, join, toData };
};

table.from = data => {
  const keys = Object.keys(data);
  const entries = [];  

  for(let i = 0; i < data[keys[0]].length; i++) {
    const entry = entries[i] = {};
    for(const key of keys)
      entry[key] = data[key][i];
  }

  return table(entries, keys);
};

在行動中:

 const table = (entries, keys) => { const toData = () => Object.fromEntries(keys.map(k => [k, entries.map(it => it[k]?? null)])); const join = (other, on) => table( entries.map(entry => ({...entry, ...(other.entries.find(other => on(entry, other))?? {}) })), [...keys, ...other.keys] ); return { entries, keys, join, toData }; }; table.from = data => { const keys = Object.keys(data); const entries = []; for(let i = 0; i < data[keys[0]].length; i++) { const entry = entries[i] = {}; for(const key of keys) entry[key] = data[key][i]; } return table(entries, keys); }; const object1 = { key1: [ 1, 1, 1, 2, 2, 3 ], key2: ['a', 'b', 'c', 'a', 'c', 'b'], prop3: ['A', 'B', 'C', 'D', 'E', 'F'] }; const object2 = { key1: [ 1, 1, 2], key2: ['a', 'c', 'a'], prop4: [10, 20, 30] }; const result = table.from(object1).join(table.from(object2), (a, b) => a.key1 === b.key1 && a.key2 === b.key2).toData(); console.log(result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM