将共享键值对上的对象与Lodash合并

时间:2016-08-21 10:06:24

标签: javascript lodash

我有两个对象数组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字段的对象(因此date: 3数组中的weather对象将被删除。

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

我认为应该可以使用unionunionBymerge或类似内容,但我在文档中找不到匹配的示例。

2 个答案:

答案 0 :(得分:2)

通过使用_.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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

答案 1 :(得分:2)

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

&#13;
&#13;
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);
&#13;
&#13;
&#13;