Javascript 使用Lodash合并共享键值对上的对象

Javascript 使用Lodash合并共享键值对上的对象,javascript,lodash,Javascript,Lodash,我有两个对象数组weather和power,我想在共享属性date上合并它们。有没有办法用lodash做到这一点 const天气=[ { 日期:二〇〇四年四月二日, 天气:2 }, { 日期:1, 天气:1 }, { 日期:2007年3月3日, 天气:3 } ]; 恒功率=[ { 日期:1, 功率:10 }, { 日期:二〇〇四年四月二日, 功率:20 }]; const merged=u.merge(天气、功率);// 通过使用索引数组创建索引对象,合并索引,并使用以下方法提取值: cons

我有两个对象数组
weather
power
,我想在共享属性
date
上合并它们。有没有办法用lodash做到这一点

const天气=[
{
日期:二〇〇四年四月二日,
天气:2
},
{
日期:1,
天气:1
},
{
日期:2007年3月3日,
天气:3
}
];
恒功率=[
{
日期:1,
功率:10
},
{
日期:二〇〇四年四月二日,
功率:20
}];

const merged=u.merge(天气、功率);// 通过使用索引数组创建索引对象,合并索引,并使用以下方法提取值:

const weather=[{“日期”:2,“天气”:2},{“日期”:1,“天气”:1},{“日期”:3,“天气”:3}];
const power=[{“日期”:1,“功率”:10},{“日期”:2,“功率”:20}];
const weatherIndex=u.keyBy(天气,“日期”);
const powerIndex=u.keyBy(power,'date');
const result=(powerIndex)
.pick(u.键(天气指数))
.merge(u.pick(weatherIndex,u.keys(powerIndex)))
.values()
.value();
控制台日志(结果)

通过索引数组创建索引对象,合并索引,并使用以下方法提取值:

const weather=[{“日期”:2,“天气”:2},{“日期”:1,“天气”:1},{“日期”:3,“天气”:3}];
const power=[{“日期”:1,“功率”:10},{“日期”:2,“功率”:20}];
const weatherIndex=u.keyBy(天气,“日期”);
const powerIndex=u.keyBy(power,'date');
const result=(powerIndex)
.pick(u.键(天气指数))
.merge(u.pick(weatherIndex,u.keys(powerIndex)))
.values()
.value();
控制台日志(结果)

虽然您几乎有了一个使用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}],
哈希=新映射,
合并=power.map(a=>{
var o={};
分配(o,a);
hash.set(a.date,o);
返回o;
});
weather.forEach(a=>hash.has(a.date)和&Object.assign(hash.get(a.date),a));

console.log(合并)虽然您几乎有了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}],
哈希=新映射,
合并=power.map(a=>{
var o={};
分配(o,a);
hash.set(a.date,o);
返回o;
});
weather.forEach(a=>hash.has(a.date)和&Object.assign(hash.get(a.date),a));

console.log(合并)几乎,它仍然包括来自
天气
日期=3
的对象,该对象在
电源中没有匹配项,应该删除。我想我们可以再次迭代
result
,检查值是否存在。我主要是想看看是否有一个很好的版本可以实现这一点,所以最好也集成它。添加一个
.filter(函数(a){return a.hasOwnProperty('weather')&&a.hasOwnProperty('power')})
确保这些属性存在。我想知道是否有更好的解决办法?!我使用pick只合并两个索引中出现的属性。几乎,它仍然包括
weather
date=3
的对象,该对象在
power
中没有匹配项,应该删除。我想我们可以再次迭代
result
,检查值是否存在。我主要是想看看是否有一个很好的版本可以实现这一点,所以最好也集成它。添加一个
.filter(函数(a){return a.hasOwnProperty('weather')&&a.hasOwnProperty('power')})
确保这些属性存在。我想知道是否有更好的解决办法?!我使用pick只合并出现在两个索引中的属性。+1因为它可以工作,但我发现它比lodash答案更难阅读。但这可能只是因为我更习惯于使用lodash,而不是新的ES功能。+1因为它确实有效,但我发现阅读lodash的答案更难。但这可能只是因为我更习惯于使用lodash,而不是新的ES功能。