Merge Array of Objects by Property using Lodash

后端 未结 7 1721
北恋
北恋 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条回答
  •  没有蜡笔的小新
    2020-12-01 06:45

    Convert the lists to objects keyed by label, merge them by _.assign, and convert it back to an array. It will even retain order of the items on most browsers.

    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'
      }
    ];
    
    console.log(
      _.map(
        _.assign(
          _.mapKeys(original, v => v.label),
          _.mapKeys(update, v => v.label)
        )
      )
    );
    
    
    // or remove more duplicated code using spread
    
    console.log(
      _.map(
        _.assign(
          ...[original, update].map(
            coll => _.mapKeys(coll, v => v.label)
          )
        )
      )
    );

提交回复
热议问题