Javascript 使用 Lodash 进行深度合并

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39246101/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:22:00  来源:igfitidea点击:

Deep Merge using Lodash

javascriptarraysmergelodash

提问by benjiman

I have two arrays of objects that contain addresses that have a label and an object for the actual address:

我有两个对象数组,其中包含具有标签的地址和实际地址的对象:

var originalAddresses = [
  {
    label: 'home',
    address: { city: 'London', zipCode: '12345' }
  },
  {
    label: 'work',
    address: { city: 'New York', zipCode: '54321' }
  }
];

var updatedAddresses = [
  {
    label: 'home',
    address: { city: 'London (Central)', country: 'UK' }
  },
  {
    label: 'spain',
    address: { city: 'Madrid', zipCode: '55555' }
  }
];

Now I want to merge these arrays by labeland compare the individual properties of the addresses and merge only the properties from the new address that are actually present. So the result should look like this:

现在我想合并这些数组label并比较地址的各个属性,并仅合并来自新地址的实际存在的属性。所以结果应该是这样的:

var result = [
  {
    label: 'home',
    address: { city: 'London (Central)', zipCode: '12345', country: 'UK' }
  },
  {
    label: 'work',
    address: { city: 'New York', zipCode: '54321' }
  },
  {
    label: 'spain',
    address: { city: 'Madrid', zipCode: '55555' }
  }
]

How can I do this using lodash?I tried a combination of unionBy()and merge(). With unionBy() I was able to compare and join the arrays by label, but this always replaces the whole object. I can sure merge the addresses but this doesn't happen by label then.

我怎样才能使用lodash做到这一点我尝试了unionBy()和的组合merge()。使用 unionBy() 我能够按标签比较和连接数组,但这总是替换整个对象。我可以肯定合并地址,但这不会通过标签发生。

回答by Ori Drori

You can turn both arrays into objects using _.keyBy(arr, 'label'), and then merge deep using _.merge():

您可以使用 将两个数组转换为对象_.keyBy(arr, 'label'),然后使用_.merge()以下方法进行深度合并:

var originalAddresses = [{
  label: 'home',
  address: {
    city: 'London',
    zipCode: '12345'
  }
}, {
  label: 'work',
  address: {
    city: 'New York',
    zipCode: '54321'
  }
}];

var updatedAddresses = [{
  label: 'home',
  address: {
    city: 'London (Central)',
    country: 'UK'
  }
}, {
  label: 'spain',
  address: {
    city: 'Madrid',
    zipCode: '55555'
  }
}];

var result = _.values(_.merge(
  _.keyBy(originalAddresses, 'label'),
  _.keyBy(updatedAddresses, 'label')
));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>