Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

javascript - Lodash对象数组的并集(Lodash union of arrays of objects)

I'd like to use the _.union function to create a union of two arrays of objects.

(我想使用_.union函数创建两个对象数组的并集。)

Union works with arrays of primitives only as it uses === to examine if two values are equal.

(Union仅在使用===来检查两个值是否相等时才与基元数组一起工作。)

I'd like to compare objects using a key property: objects with the same key property would be regarded equal.

(我想使用key属性比较对象:具有相同key属性的对象将被视为相等。)

Is there a nice functional way to achieve that ideally using lodash?

(有没有一种理想的功能性方法可以使用lodash理想地实现这一目标?)

  ask by Janos translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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() :

(另一种方法是使用flatten()uniq() :)

var union = _.uniq(_.flatten([array1, array2]), matcherFn);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...