由于不喜欢这种方法,我正在寻找有关如何改进此方法的建议。
我有两个带有Json的对象数组。
第一个列表具有日期范围内的所有日期,第二个列表来自SQL查询,其中可能缺少几个月。
期望的结果必须是一个包含所有月份的清单,并带有事宜计数,但是当我将它们加载到下面的函数中时,我缺少了清单中不存在的月份的问题计数。
我认为我只是在该函数中缺少了一些代码,但是我不确定是什么,因此来到这里。
我确实在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"}];
答案 0 :(得分:1)
||
设置默认值如何?
const merge = (x, y) =>
x.map(xItem => ({
...y.find(yItem => yItem.labelDate === xItem.labelDate && yItem) || {...xItem, matterCount: "0"}
}));
另一种方法是简单地添加默认值,该默认值将被yItem
覆盖:
const merge = (x, y) =>
x.map(xItem => ({
...xItem,
...{matterCount: "0"},
...y.find(yItem => yItem.labelDate === xItem.labelDate && yItem)
}));