【发布时间】:2020-12-10 14:19:56
【问题描述】:
这是一个例子: 我的第一个数组:
var array1= [
{"dt":"20:25","al":"my test","totalprice":4180,"curr":"INR","duration":"0:00:00","dates":"2020-12-10"},
{"dt":"22:45","al":"my test","totalprice":4180,"curr":"INR","duration":"0:00:00","dates":"2020-12-10"},
{"dt":"19:15","al":"my test","totalprice":6043,"curr":"INR","duration":"0:00:00","dates":"2020-12-12"}]
第二个数组:
var array2 = [
{
date: '2020-12-10',
al: 'my test',
totalprice: null,
curr: null,
dt: null,
duration: null
},
{
date: '2020-12-11',
al: 'my test',
totalprice: null,
curr: null,
dt: null,
duration: null
},
{
date: '2020-12-12',
al: 'my test',
totalprice: null,
curr: null,
dt: null,
duration: null
}
]
我希望日期的array2 与array1 匹配,并将array1 的所有相应对象与匹配的日期相加作为结果,对于不匹配的日期,必须使用array2 对象。 日期 2020-12-11 已从 array2 用作 null,因为我们在 array1 中没有日期,而其他日期在 array1 上。
我的代码:
finalresult = array2.map(item => item ? {...item, ...array1.filter(mrd=> mrd.dates === item.date) }: {})
console.log(finalresult)
结果:
[
{
'0': {
dt: '20:25',
al: 'my test',
totalprice: 4180,
curr: 'INR',
duration: '0:00:00',
dates: '2020-12-10'
},
'1': {
dt: '22:45',
al: 'my test',
totalprice: 4180,
curr: 'INR',
duration: '0:00:00',
dates: '2020-12-10'
},
date: '2020-12-10',
al: 'my test',
totalprice: null,
curr: null,
dt: null,
duration: null
},
{
date: '2020-12-11',
al: 'my test',
totalprice: null,
curr: null,
dt: null,
duration: null
},
{
'0': {
dt: '19:15',
al: 'my test',
totalprice: 6043,
curr: 'INR',
duration: '0:00:00',
dates: '2020-12-12'
},
date: '2020-12-12',
al: 'my test',
totalprice: null,
curr: null,
dt: null,
duration: null
}
]
我需要这样的结果:
[{
dt: '20:25',
al: 'my test',
totalprice: 4180,
curr: 'INR',
duration: '0:00:00',
dates: '2020-12-10'
},
{
dt: '22:45',
al: 'my test',
totalprice: 4180,
curr: 'INR',
duration: '0:00:00',
dates: '2020-12-10'
},
{
date: '2020-12-11',
al: 'my test',
totalprice: null,
curr: null,
dt: null,
duration: null
},
{
dt: '19:15',
al: 'my test',
totalprice: 6043,
curr: 'INR',
duration: '0:00:00',
dates: '2020-12-12'
}]
谁能帮我解决这个问题
【问题讨论】:
-
你当前的代码返回什么?
-
它在所有迭代中添加 array2 对象。但我只需要当array2 日期不在array1 中时。它返回带有键值的过滤器。
-
{ ...item, ...array1.filter(...) }你在一个对象字面量中传播一个数组。这将创建filter返回的数组的项目和数字索引的对象属性 -
任何其他可能的解决方法。
-
@GalaxyCat105 我已经添加了我的回复。
标签: javascript node.js arrays