将共享键值对上的对象与Lodash合并 [英] Merge objects on shared Key Value Pair with Lodash
问题描述
我有两个对象数组 weather
和 power
我希望在共享属性上合并日期
。有没有办法用lodash做到这一点?
const weather = [
{
日期:2,
天气:2
},
{
日期:1,
天气:1
},
{
日期:3,
天气:3
}
];
const power = [
{
date:1,
power:10
},
{
date:2 ,
功率:20
}];
const merged = _.merge(天气,力量); //< - 这不符合预期的
预期输出仅包含具有的对象一个匹配的日期
字段(所以天气中的
数组被删除)。日期:3
对象
const expected = [{
date: 1,
天气:1,
功率:10
},
{
日期:2,
天气:2,
功率: 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)))。value()。value(); console.log(结果) );
< script src =https:// cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js\"></script>
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.
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>
这篇关于将共享键值对上的对象与Lodash合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!