合并基于JSON数组日期的JavaScript
假设我们有以下对象数组-
const arr = [
{
"date" : "2010-01-01",
"price" : 30
},
{
"date" : "2010-02-01",
"price" : 40
},
{
"date" : "2010-03-01",
"price" : 50
},
{
"date" : "2010-01-01",
"price2" : 45
},
{
"date" : "2010-05-01",
"price2" : 40
},
{
"date" : "2010-10-01",
"price2" : 50
}
];我们需要编写一个包含一个这样的数组的JavaScript函数。然后,该函数应根据对象的“日期”属性合并对象。
示例
const arr = [
{
"date" : "2010-01-01", "price" : 30
},
{
"date" : "2010-02-01",
"price" : 40
},
{
"date" : "2010-03-01",
"price" : 50
},
{
"date" : "2010-01-01",
"price2" : 45
}, {
"date" : "2010-05-01",
"price2" : 40
},
{
"date" : "2010-10-01",
"price2" : 50
}
];
const mergeArray = (arr = []) => {
const data = arr.slice();
data.sort((a, b) => new Date(a.date) - new Date(b.date))
const res = []
data.forEach(el => {
if(!this[el.date]) {
this[el.date] = {
date: el.date,
price: null,
price2: null
}
res.push(this[el.date])
}
this[el.date] = Object.assign(this[el.date], el)
});
return res;
}
console.log(JSON.stringify(mergeArray(arr), undefined, 4));输出结果
控制台中的输出将是-
[
{
"date": "2010-01-01",
"price": 30,
"price2": 45
},
{
"date": "2010-02-01",
"price": 40,
"price2": null
},
{
"date": "2010-03-01",
"price": 50,
"price2": null
},
{
"date": "2010-05-01",
"price": null,
"price2": 40
},
{
"date": "2010-10-01",
"price": null,
"price2": 50
}
]