我有两个对象数组 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
字段的对象(因此 weather
数组中的 date: 3
对象被丢弃).
const expected = [{
date: 1,
weather: 1,
power: 10
},
{
date: 2,
weather: 2,
power: 20
}];
我觉得这应该可以通过 union
、unionBy
、merge
或类似的方式实现,但我在文档中找不到匹配的示例.
最佳答案
通过使用 _.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>
关于javascript - 使用 Lodash 合并共享键值对上的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39063031/