使用lodash合并两个数组中的对象 [英] Merge objects inside the two arrays using lodash

查看:3260
本文介绍了使用lodash合并两个数组中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将两个数组合并为一个. 第一个具有默认配置,第二个具有实际配置. 我在此处发现了非常相似的问题,但在我的特定情况下,它不起作用.

I am trying to merge two arrays into one. First one has default configuration and the second one has actual one. I found very similar problem here, but in my specific case it does not work.

默认配置:

[
  { configurationOption: 'X provisioning', platform: 'X', value: true },
  { configurationOption: 'Y provisioning', platform: 'Y', value: true },
  { configurationOption: 'Z provisioning', platform: 'Z', value: true }
]

实际配置:

[
  { platform: 'X', value: false },
  { platform: 'Y', value: true }
]

预期结果:

[
  { configurationOption: 'X provisioning', platform: 'X', value: false },
  { configurationOption: 'Y provisioning', platform: 'Y', value: true },
  { configurationOption: 'Z provisioning', platform: 'Z', value: true }
]

因此,基本上需要做的是更新默认配置的值"属性,基于实际情况,棘手的部分是某些配置项在实际配置中不存在,并且实际配置缺少"configurationOption"属性.

So basically what it needs to do is update 'value' property of default configuration, based on actual one, tricky part is that some of configurationItem does not exist in actual configuration and actual configuration is missing 'configurationOption' property.

var config = _.unionBy(actual, defaultConf, 'platform');

这行是我能得到的最接近的行,但是缺少'configurationOption'属性.

This line is the closest one I could get, but is missing 'configurationOption' property.

这里是CodePen,因此您可以使用它: https://codepen. io/anon/pen/oBwLMb?editors = 0012

Here is CodePen so you can play around with it: https://codepen.io/anon/pen/oBwLMb?editors=0012

推荐答案

基于defaults创建新的对象数组,其中每个元素都是将默认值与actuals中找到的相应实际数据合并的结果,基于匹配的platform.

Create a new array of objects based on defaults, each element of which is the result of merging that default with the corresponding actual data found in actuals, based on matching platform.

const defaults = [
  {configurationOption: 'X provisioning', platform: 'X', value: true}, 
  {configurationOption: 'Y provisioning', platform: 'Y', value: true}, 
  {configurationOption: 'Z provisioning', platform: 'Z', value: true}];

const actuals = [
  {platform: 'X', value: false}, 
  {platform: 'Y', value: true}];

var result = defaults.map(deflt => Object.assign(
  {}, 
  deflt, 
  actuals.find(actual => actual.platform === deflt.platform)));

console.log(result);
      

如果愿意,可以使用lodash将其重写,可以使用_.map_.assign_.find.

This could be rewritten using lodash if you so prefer, using _.map, _.assign, and _.find.

这篇关于使用lodash合并两个数组中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆