gpt4 book ai didi

javascript - 根据唯一 ID 合并两个数组

转载 作者:行者123 更新时间:2023-12-02 23:41:28 25 4
gpt4 key购买 nike

我正在寻找一些有关如何改进此方法的建议,因为我不喜欢这种解决方法。

我有两个带有 Json 的对象数组。

第一个列表包含某个日期范围内的所有日期,第二个列表来自 SQL 查询,其中可能缺少一些月份。

所需的结果需要是一个包含所有月份的列表,其中包含一个 MatterCount,但是当我将它们加载到下面的函数中时,我丢失了列表中不存在的月份的 MatterCount。

我认为我只是在函数中遗漏了一点代码,但我不完全确定是什么,因此来到这里。

我确实在 JSFiddle 中有一个解决方法,但我更喜欢更清晰的代码。

let x = [{labelDate: "Jun 2013"},
{labelDate: "Jul 2013"},
{labelDate: "Aug 2013"},
{labelDate: "Sep 2013"},
{labelDate: "Oct 2013"},
{labelDate: "Nov 2013"},
{labelDate: "Dec 2013"},
{labelDate: "Jan 2014"},
{labelDate: "Feb 2014"},
{labelDate: "Mar 2014"},
{labelDate: "Apr 2014"},
{labelDate: "May 2014"}];


let y = [{labelDate: "Jun 2013", matterCount: "1"},
{labelDate: "Jul 2013", matterCount: "2"},
{labelDate: "Aug 2013", matterCount: "2"},
{labelDate: "Sep 2013", matterCount: "10"},
{labelDate: "Oct 2013", matterCount: "1"},
{labelDate: "Nov 2013", matterCount: "1"},
{labelDate: "Feb 2014", matterCount: "1"},
{labelDate: "Apr 2014", matterCount: "17"},
{labelDate: "May 2014", matterCount: "21"}];

const merge = (x, y) =>
x.map(xItem => ({
...y.find(yItem => yItem.labelDate === xItem.labelDate && Item),
...xItem
}));

Actual outcome
merge = [{labelDate: "Jun 2013", matterCount: "1"},
{labelDate: "Jul 2013", matterCount: "2"},
{labelDate: "Aug 2013", matterCount: "2"},
{labelDate: "Sep 2013", matterCount: "10"},
{labelDate: "Oct 2013", matterCount: "1"},
{labelDate: "Nov 2013", matterCount: "1"},
{labelDate: "Dec 2013"},
{labelDate: "Jan 2014"},
{labelDate: "Feb 2014", matterCount: "1"},
{labelDate: "Mar 2014"},
{labelDate: "Apr 2014", matterCount: "17"},
{labelDate: "May 2014", matterCount: "21"}];

desired outcome
merge = [{labelDate: "Jun 2013", matterCount: "1"},
{labelDate: "Jul 2013", matterCount: "2"},
{labelDate: "Aug 2013", matterCount: "2"},
{labelDate: "Sep 2013", matterCount: "10"},
{labelDate: "Oct 2013", matterCount: "1"},
{labelDate: "Nov 2013", matterCount: "1"},
{labelDate: "Dec 2013", matterCount: "0"},
{labelDate: "Jan 2014", matterCount: "0"},
{labelDate: "Feb 2014", matterCount: "1"},
{labelDate: "Mar 2014", matterCount: "0"},
{labelDate: "Apr 2014", matterCount: "17"},
{labelDate: "May 2014", matterCount: "21"}];

https://jsfiddle.net/cp39aoyf/2/

最佳答案

||设置默认值怎么样:

const merge = (x, y) =>
x.map(xItem => ({
...y.find(yItem => yItem.labelDate === xItem.labelDate && yItem) || {...xItem, matterCount: "0"}
}));

Demo JSFiddle.

另一种方法是简单地添加默认值,该值将被 yItem 覆盖(如果存在):

const merge = (x, y) =>
x.map(xItem => ({
...xItem,
...{matterCount: "0"},
...y.find(yItem => yItem.labelDate === xItem.labelDate && yItem)
}));

Fiddle for this one.

关于javascript - 根据唯一 ID 合并两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56053803/

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