合并基于日期的 JavaScript JSON 数组
javascriptweb developmentfront end technologyobject oriented programmingjson
假设,我们有以下对象数组 −
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 函数来接收一个这样的数组。然后该函数应根据对象的"date"属性合并对象。
示例
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 } ]