Javascript Lodash 对象数组的并集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29320817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Lodash union of arrays of objects
提问by Janos
I'd like to use the _.unionfunction to create a union of two arrays of objects. Union works with arrays of primitives only as it uses === to examine if two values are equal.
我想使用该_.union函数来创建两个对象数组的联合。Union 仅适用于原始数组,因为它使用 === 检查两个值是否相等。
I'd like to compare objects using a key property: objects with the same key property would be regarded equal. Is there a nice functional way to achieve that ideally using lodash?
我想使用键属性比较对象:具有相同键属性的对象将被视为相等。有没有一种很好的功能方法可以理想地使用 lodash 实现这一目标?
采纳答案by Craig Suchanec
A non pure lodash way to do this but using the array.concat function you are able to do this pretty simply along uniq():
一种非纯 lodash 方法来做到这一点,但使用 array.concat 函数,你可以非常简单地做到这一点uniq():
var objUnion = function(array1, array2, matcher) {
var concated = array1.concat(array2)
return _.uniq(concated, false, matcher);
}
An alternative approach would be to use flatten()and uniq():
var union = _.uniq(_.flatten([array1, array2]), matcherFn);
回答by MatthieuH
And what about UniqBywith a concat of the two arrays before?
那么UniqBy之前的两个数组的连接呢?
import _ from 'lodash'
const arrayUnion = (arr1, arr2, identifier) => {
const array = [...arr1, ...arr2]
return _.uniqBy(array, identifier)
}
const array1 = [{ id: 1 }, { id: 2 }, { id: 3 }]
const array2 = [{ id: 3 }, { id: 4 }, { id: 4 }]
console.log(arrayUnion(array1, array2, 'id'))
result→ [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 4 }]
结果→ [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 4 }]
回答by alaboudi
Late to the party but _.unionWith is much better in doing what you want.
聚会迟到了,但 _.unionWith 在做你想做的事情上要好得多。
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.unionWith(objects, others, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
回答by olegzhermal
_.unionBy(array1, array2, matcherFn);
_.unionBy(array1, array2, matcherFn);
回答by crapthings
lodash merge object from arrays
lodash 从数组合并对象
const test1 = [
{ name: 'zhanghong', age: 32, money: 0, size: 12, },
{ name: 'wanghong', age: 20, size: 6 },
{ name: 'jinhong', age: 16, height: 172 },
]
const test2 = [
{ name: 'zhanghong', gender: 'male', age: 14 },
{ name: 'wanghong', gender: 'female', age: 33 },
{ name: 'lihong', gender: 'female', age: 33 },
]
const test3 = [
{ name: 'meinv' },
]
const test4 = [
{ name: 'aaa' },
]
const test5 = [
{ name: 'zhanghong', age: 'wtf' },
]
const result = mergeUnionByKey(test1, test2, test3, test4, [], test5, 'name', 'override')
function mergeUnionByKey(...args) {
const config = _.chain(args)
.filter(_.isString)
.value()
const key = _.get(config, '[0]')
const strategy = _.get(config, '[1]') === 'override' ? _.merge : _.defaultsDeep
if (!_.isString(key))
throw new Error('missing key')
const datasets = _.chain(args)
.reject(_.isEmpty)
.filter(_.isArray)
.value()
const datasetsIndex = _.mapValues(datasets, dataset => _.keyBy(dataset, key))
const uniqKeys = _.chain(datasets)
.flatten()
.map(key)
.uniq()
.value()
return _.chain(uniqKeys)
.map(val => {
const data = {}
_.each(datasetsIndex, dataset => strategy(data, dataset[val]))
return data
})
.filter(key)
.value()
}
console.log(JSON.stringify(result, null, 4))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
回答by Pravin Divraniya
- Compare objects using a key property:-
- 使用键属性比较对象:-
_.unionBy(array1,array2,'propname');
_.unionBy(array1,array2,'propname');
- Compare objects using all key property:-
- 使用所有关键属性比较对象:-
_.unionWith(array1,array2, _.isEqual);
_.unionWith(array1,array2, _.isEqual);
- Compare objects using a string key property in case insensitive way:-
- 以不区分大小写的方式使用字符串键属性比较对象:-
_.unionWith(array1,array2, function(obj,other){ return obj.propname.toLowercase() === other.propname.toLowercase(); });
_.unionWith(array1,array2, function(obj,other){ return obj.propname.toLowercase() === other.propname.toLowercase(); });
propnameis name of key property of your object.
propname是对象的关键属性的名称。

