Merge Array of Objects by Property using Lodash

后端 未结 7 1689
北恋
北恋 2020-12-01 06:25

I have two arrays of objects that represent email addresses that have a label and a value:

var original = [
  {
    label: \'private\',
    value: \'private@         


        
7条回答
  •  Happy的楠姐
    2020-12-01 06:48

    _.unionBy():
    This method is like _.union except that it accepts iteratee which is invoked for each element of each arrays to generate the criterion by which uniqueness is computed. Result values are chosen from the first array in which the value occurs.

    var original = [
      { label: 'private', value: 'private@johndoe.com' },
      { label: 'work', value: 'work@johndoe.com' }
    ];
    
    var update = [
      { label: 'private', value: 'me@johndoe.com' },
      { label: 'school', value: 'schol@johndoe.com' }
    ];
    
    var result = _.unionBy(update, original, "label");
    
    console.log(result);

提交回复
热议问题