【问题标题】:Merge objects on shared Key Value Pair with Lodash使用 Lodash 合并共享键值对上的对象
【发布时间】:2016-12-28 00:44:26
【问题描述】:

我有两个对象数组weatherpower,我想在共享属性date 上合并它们。有没有办法用 lodash 做到这一点?

 const weather = [
  {
    date: 2,
    weather: 2
  },
  {
    date: 1,
    weather: 1
  },
  {
    date: 3,
    weather: 3
  }
  ];

  const power = [
  {
    date: 1,
    power: 10
  },
  {
    date: 2,
    power: 20
  }];

  const merged = _.merge(weather, power); // <- This does not work as hoped for

预期的输出仅包含具有匹配 date 字段的对象(因此删除了 weather 数组中的 date: 3 对象)。

  const expected = [{
    date: 1,
    weather: 1,
    power: 10
  },
  {
    date: 2,
    weather: 2,
    power: 20
  }];

我觉得 unionunionBymerge 或类似的应该可以做到这一点,但我在文档中找不到匹配的示例。

【问题讨论】:

    标签: javascript lodash


    【解决方案1】:

    使用_.keyBy('date')索引数组创建索引对象,合并索引,使用_.values()提取值:

    const weather = [{"date":2,"weather":2},{"date":1,"weather":1},{"date":3,"weather":3}];
    
    const power = [{"date":1,"power":10},{"date":2,"power":20}];
    
    const weatherIndex = _.keyBy(weather, 'date');
    const powerIndex = _.keyBy(power, 'date');
    
    const result = _(powerIndex)
      .pick(_.keys(weatherIndex))
      .merge(_.pick(weatherIndex, _.keys(powerIndex)))
      .values()
      .value();
    
    console.log(result);
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"&gt;&lt;/script&gt;

    【讨论】:

    • 几乎,它仍然包含来自weather 的带有date=3 的对象,该对象在power 中没有匹配项,应该被删除。我想可以再次遍历result 并检查值是否存在。我主要是想看看是否有一个漂亮的版本可以做到这一点,所以最好也集成它。
    • 添加.filter(function(a){return a.hasOwnProperty('weather') &amp;&amp; a.hasOwnProperty('power')}) 确保这些属性存在。我想知道是否有更好的解决方案?!
    • 我使用 pick 只合并出现在两个索引中的属性。
    【解决方案2】:

    虽然您几乎可以使用 lodash 解决方案,但您可以在纯 Javascript 中使用带有哈希表和两个数组循环的提案。

    var weather = [{ date: 2, weather: 2 }, { date: 1, weather: 1 }, { date: 3, weather: 3 }],
        power = [{ date: 1, power: 10 }, { date: 2, power: 20 }],
        hash = new Map,
        merged = power.map(a => {
            var o = {};
            Object.assign(o, a);
            hash.set(a.date, o);
            return o;
        });
    
    weather.forEach(a => hash.has(a.date) && Object.assign(hash.get(a.date), a));
    console.log(merged);

    【讨论】:

    • +1 因为它有效,但我发现它比 lodash 答案更难阅读。但这可能只是我更习惯于 lodash 而不是新的 ES 功能。
    猜你喜欢
    • 2018-08-07
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 2018-05-27
    • 1970-01-01
    • 2016-06-12
    相关资源
    最近更新 更多