问题
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