我如何根据相似的字段检查合并两个对象数组数据

how i can merge two object array data based on the similar filed checking

我有两个包含低值和高值的对象数组,我如何通过检查相似的文件(如日期)合并它们并将它们合并为低值和高值以及 return 一个数组。

data = {
    low: [
        { date: '2020-09-17', value: '50' },
        { date: '2020-09-18', value: '52' },
        { date: '2020-09-15', value: '45' },
    ],

    high: [
        { date: '2020-09-17', value: '70' },
        { date: '2020-09-18', value: '75' },
        { date: '2020-09-15', value: '80' },
    ],
};

// Expected Output new array with date sort:
[
    { date: '2020-09-18', value: '52/75' },
    { date: '2020-09-17', value: '70/50' },
    { date: '2020-09-15', value: '45/80' },
];

您可以使用 mapfindsort

const res = data.low.map(l => ({
  date: l.date,
  value: `${l.value}/${data.high.find(h => h.date === l.date).value}`
})).sort((a,b) => b.date.localeCompare(a.date))

const data = {
  low: [
      { date: '2020-09-17', value: '50' },
      { date: '2020-09-18', value: '52' },
      { date: '2020-09-15', value: '45' },
  ],

  high: [
      { date: '2020-09-17', value: '70' },
      { date: '2020-09-18', value: '75' },
      { date: '2020-09-15', value: '80' },
  ],
};

const res = data.low.map(l => ({
  date: l.date,
  value: `${l.value}/${data.high.find(h => h.date === l.date).value}`
})).sort((a,b) => b.date.localeCompare(a.date))

console.log(res)
.as-console-wrapper { max-height: 100% !important; }

这可以通过 Array.map() and Array.find() 实现,如下所示:

data = {
    low: [
        { date: '2020-09-17', value: '50' },
        { date: '2020-09-18', value: '52' },
        { date: '2020-09-15', value: '45' },
    ],
    high: [
        { date: '2020-09-17', value: '70' },
        { date: '2020-09-18', value: '75' },
        { date: '2020-09-15', value: '80' },
    ],
};

let result = data.low.map(oLow => {
  oLow.value += '/' + data.high.find(oHigh => oHigh.date == oLow.date).value;
  return oLow;
});
result.sort((a, b) => new Date(b.date) - new Date(a.date));

console.log(result);