gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:45:29 27 4
gpt4 key购买 nike

我有两个对象数组 weatherpower,我想将它们合并到共享属性 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
}];

我觉得这应该可以通过 unionunionBymerge 或类似的方式实现,但我在文档中找不到匹配的示例.

最佳答案

通过使用 _.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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com