简体   繁体   English

Lodash - 如何根据键合并两个对象数组?

[英]Lodash - How to merge two arrays of objects based on key?

I'm trying to concat two arrays of objects with lodash.我正在尝试用 lodash 连接两个对象数组。 I have these two array and I use concat operator in this way:我有这两个数组,我以这种方式使用 concat 运算符:

 var array1 = [{ id: 1, name: 'doc1' }, { id: 2, name: 'doc2' }];
 var array2 = [{id:1, name:'doc1'}, {id:3, name:'doc3'}, {id:4, name:'doc4'}];

 var array3 = _.concat(array1, array2);

I would like an array like this我想要一个这样的数组

 [{id:1, name:'doc1'}, {id:2, name:'doc2'}, {id:3, name:'doc3'}, {id:4, name:'doc4'}]]

But with concat function I obtain an array like this:但是通过 concat 函数,我得到了一个这样的数组:

  [{ id: 1, name: 'doc1' }, { id: 1, name: 'doc1' }, { id: 2, name: 'doc2' }, { id: 3, name: 'doc3' }, { id: 4, name: 'doc4' }]]

I want to avoid the repetition of an object with the same id...Which kind of operator can I use?我想避免重复具有相同 id 的对象...我可以使用哪种运算符?

You can get the result using merge and keyBy lodash functions.您可以使用mergekeyBy lodash 函数获得结果。

 var array1 = [{id:1, name:'doc1'}, {id:2, name:'doc2'}]; var array2 = [{id:1, name:'doc1'}, {id:3, name:'doc3'}, {id:4, name:'doc4'}]; var merged = _.merge(_.keyBy(array1, 'id'), _.keyBy(array2, 'id')); var values = _.values(merged); console.log(values);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

Use _.unionBy() to combine two arrays, and remove duplicates that have the same unique field ( id in this case).使用_.unionBy()组合两个数组,并删除具有相同唯一字段(在本例中为id )的重复项。 The lodash's union methods create an array of unique values. lodash 的 union 方法创建一个唯一值数组。 The _.unionBy() method accepts an iteratee which is invoked for each element of each array to generate the criterion by which uniqueness is computed. _.unionBy()方法接受一个 iteratee,它为每个数组的每个元素调用以生成计算唯一性的标准。

 const array1 = [{id:1, name:'doc1'}, {id:2, name:'doc2'}]; const array2 = [{id:1, name:'doc1'}, {id:3, name:'doc3'}, {id:4, name:'doc4'}]; const result = _.unionBy(array1, array2, 'id'); console.log(result);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

You have uniqWith in lodash that allows you to do this: https://lodash.com/docs#uniqWith您在 lodash 中有 uniqWith 允许您执行此操作: https ://lodash.com/docs#uniqWith

 var array1 = [{id:1, name:'doc1'}, {id:2, name:'doc2'}]; var array2 = [{id:1, name:'doc1'}, {id:3, name:'doc3'}, {id:4, name:'doc4'}]; var values = _.uniqWith([...array1, ...array2], _.isEqual); console.log(values);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM