我有两个对象数组weather
和power
,我想在共享属性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
}];
我认为应该可以使用union
,unionBy
,merge
或类似内容,但我在文档中找不到匹配的示例。
答案 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中使用一个带有哈希表和两个数组循环的提议。
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;