JavaScript:两个数组的类SQL连接

问题描述

我有这样的数组:

const one = [
  {id: 1,field1: "a"},{id: 2,field1: "b"},{id: 3,field1: "c"},{id: 4,field1: "d"}
]

const two = [
  {id: 4,field2: "4"},{id: 1,field1: "1"}
]
// what I want to achieve:
const result = [
  {id: 1,field1: "a",field2: "1"},field1: "d",field2: "4"}
]

我想合并一个和两个,所以得到结果。这与sql连接非常相似,但是我想在JavaScript代码中完成所有这些操作。注意:

  1. 这是id“列”的“加入”。
  2. 结果的顺序是one数组的顺序(按ID排序恰好是相同的顺序)
  3. 两个数组中的字段都存在于结果中

我已经找到了自己的方法,但是代码很笨拙,很难阅读。基本上,您过滤one删除two中不存在的元素,然后映射到one并合并two数组的字段。

是否有更简洁的方法来实现这一目标?我正在使用lodash,我希望在那里有一个函数可以简化此操作,但是我还没有找到任何函数

解决方法

通过键(const joinBy = (arr1,arr2,key) => { const arr2Dict = _.keyBy(arr2,key) return arr1 .filter(item => item[key] in arr2Dict) .map(item => ({ ...item,...arr2Dict[item[key]] })) } const one = [{id: 1,field1: "a"},{id: 2,field1: "b"},{id: 3,field1: "c"},{id: 4,field1: "d"}] const two = [{id: 4,field2: "4"},{id: 1,field2: "1"}]; const result = joinBy(one,two,'id') console.log(result))创建第二个数组的字典或Map,然后过滤第一个数组,并仅保留出现在字典中的项目。然后,映射其余项目,并从字典中添加相关项目。

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>
_.keyBy()

如果不想使用lodash,则可以轻松替换Array.reduce(),并使用Array.map()创建对象或使用const joinBy = (arr1,key) => { const arr2Dict = new Map(arr2.map(o => [o[key],o])) return arr1 .filter(item => arr2Dict.has(item[key])) .map(item => ({ ...item,...arr2Dict.get(item[key]) })) } const one = [{id: 1,'id') console.log(result)创建Map。

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>
const signedTranserTx = transfer(
    {
        type: 4,version: 2,amount: 10000,recipient: "3MqfoN68Gj3Eqc9C7pHLqbYvd5k2hovSkgi",attachment: codedAttachment
    },{privateKey: privateKey}
);

,

您可以使用merge中的mapfindlodash函数。用于排序-sortBy

_.sortBy(
   _.map(two,(n) => _.merge(n,_.find(one,['id',n.id]))),(o) => _.findIndex(one,o.id]),);

const one = [{id: 1,field1: "d"}],two = [{id: 4,field2: "1"}];

const r = _.sortBy(
   _.map(two,);

console.log(r);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>

,

如果您具有不同的字段,则可以将带有引用项的对象作为对象并映射two并按id排序。

const
    one = [{ id: 1,field1: "a" },{ id: 2,field1: "b" },{ id: 3,field1: "c" },{ id: 4,field1: "d" }],two = [{ id: 4,field2: "4" },{ id: 1,field2: "1" }],fromOne = Object.fromEntries(one.map((object,index) => [object.id,{ object,index }])),result = two
        .map(o => ({ ...fromOne[o.field2].object,...o }))
        .sort((a,b) => fromOne[a.field2].index - fromOne[b.field2].index);
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }