Merge objects on shared Key Value Pair with Lodash

落爺英雄遲暮 提交于 2019-12-08 08:00:00

问题


I have two arrays of objects weather and power that I would like to merge on the shared property date. Is there a way to do this with 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

The expected output contains only the objects that have a matching date field (so the date: 3 object from the weather array is dropped).

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

I feel like this should be possible with union, unionBy, merge or similar but I could not find a matching example in the documentation.


回答1:


Create index object by indexing the arrays using _.keyBy('date'), merge the indexes, and extract the values using _.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>



回答2:


While you have almost a solution with lodash, you could use in plain Javascript a proposal with a hash table and two loops for the arrays.

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);


来源:https://stackoverflow.com/questions/39063031/merge-objects-on-shared-key-value-pair-with-lodash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!