如何在 React JS 中组合具有相同日期的数组

我有一个数组:


data = [ {date: 4/15/2020, 9:46:07 PM, value: "abc"},

         {date: 4/15/2020, 11:19:18 PM, value: "xyz"},

         {date: 4/16/2020, 1:25:13 PM, value: "def"},

         {date: 4/17/2020, 5:6:17 PM, value: "pqr"}

       ];

我必须比较日期对象并合并数组。


因此,预期的输出如下所示:


 data = [ {date: 4/15/2020, value: ["abc", "xyz"]},

         {date: 4/16/2020, value: ["def"]},

         {date: 4/17/2020, value: ["pqr"]}

       ];

我怎样才能做到这一点?


提前致谢!!


当年话下
浏览 76回答 3
3回答

莫回无

我的方法:   data = [ {date: 4/15/2020, 9:46:07 PM, value: "abc"},             {date: 4/15/2020, 11:19:18 PM, value: "xyz"},             {date: 4/16/2020, 1:25:13 PM, value: "def"},             {date: 4/17/2020, 5:6:17 PM, value: "pqr"}           ];    // Create a map for the dates    let dataMap = {};    data.forEach((el) => {      let tempDate = getDateFormat(el.date);      if (tempDate in dateMap) {        dateMap[tempDate].value.push(el.value);      } else {        dateMap[tempDate] = {          date: tempDate,          value: [el.value],        };      }    });    data = [];   // Fill the data    Object.keys(dataMap).forEach((el) => data.push(dataMap[el]));   // The format of date    function getDateFormat(date) {      return (        date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear()      );    }

倚天杖

使用非常方便reduceconst data = [  {date: "4/15/2020, 9:46:07 PM", value: "abc"},  {date: "4/15/2020, 11:19:18 PM", value: "xyz"},  {date: "4/16/2020, 1:25:13 PM", value: "def"},  {date: "4/17/2020, 5:6:17 PM", value: "pqr"}]const newArray = data.reduce((acc, dt) => {  const date = new Date(dt.date)  const y = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(date)  const m = new Intl.DateTimeFormat('en', { month: 'numeric' }).format(date)  const d = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(date)    const formatedDate = `${m}/${d}/${y}`   const dateAcc = acc[formatedDate]  if (!dateAcc) {    acc[formatedDate] = {      date: formatedDate,      value: [dt.value]    }  } else {    acc[formatedDate].value.push(dt.value)  }  return acc}, {})console.log(newArray)

子衿沉夜

const res = []for (let i = 0; i < data.length; i++) {&nbsp; if (res.every(r => r.date !== data[i].date)) {&nbsp; &nbsp; res.push(data[i])&nbsp; } else {&nbsp; &nbsp; const index = res.findIndex(r => r.date == data[i].date)&nbsp; &nbsp; res[index] = {...res[index], value: [res[index].value, data[i].value]}&nbsp; }}console.log(res)它的工作原理是 id 在 data.value 中有一个值
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript