Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

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
   }
]