Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Hợp nhất mảng JSON dựa trên ngày tháng trong JavaScript

Giả sử chúng ta có mảng đối tượng sau:

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

Chúng ta cần viết hàm JavaScript nhận vào mảng này. Hàm hợp nhất các đối tượng dựa trên thuộc tính "date".

Ví dụ

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));

Kết quả

Kết quả in ra console:

[ 
  { 
    "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 
  } 
]