将对象数组转换成按月和年分组的对象数组

时间:2019-02-21 14:03:30

标签: javascript arrays

您好,我正在尝试转换对象数组,并按月和年对它们进行分组。我已经实现了转型,得到了我需要的月份和年份,但是并不是所有的项目都进入了我的团队。

我的代码:

const data = [
  {text:"Lorem 1 ipsum", date:"Thu Feb 21 2019 11:44:24 GMT+0000 (GMT)"},
  {text:"Lorem 2 ipsum", date:"Thu Feb 21 2019 11:44:24 GMT+0000 (GMT)"},
  {text:"Lorem 3 ipsum", date:"Thu Mar 21 2019 11:44:24 GMT+0000 (GMT)"},
]
const texts = [];
const formattedData = data.reduce((acc, { date, text }) => {
  const dateObj = new Date(date);
  const monthYearFormat = dateObj
    .toLocaleString("en-us", { month: "long", year: 'numeric' });

  if(acc[monthYearFormat]) {
    texts.push(text);

    acc[monthYearFormat] = {
      text: texts
    }
  } else {
    acc[monthYearFormat] = {
      text: [text]
    }
  }

  return acc;
}, {})

console.log(formattedData)

我从中得到的结果是:

{
  February 2019: {
   text: ['Lorem 2 ipsum']
  },
  March 2019: {
   text: ['Lorem 3 ipsum']
  }
}

虽然它似乎正在替换我的第一个对象。二月还应包含“ Lorem 1 ipsum”,如下所示:

{
  February 2019: {
   text: ['Lorem 1 ipsum', 'Lorem 2 ipsum']
  },
  March 2019: {
   text: ['Lorem 3 ipsum']
  }
}

有什么想法我在这里出错吗?预先谢谢你。

2 个答案:

答案 0 :(得分:4)

代替

test1.main()

尝试

if(acc[monthYearFormat]) {
  texts.push(text);

  acc[monthYearFormat] = {
    text: texts
  }
}

答案 1 :(得分:0)

有两种方法。第二个只是使用 reduce 的乐趣,因为原始代码使用了 reduce 。另外,请考虑推送原始对象(在这种情况下为 entry ),这样您不仅拥有文本,而且还拥有原始的日期(如果需要)。

const data = [
    { text: "Lorem 1 ipsum", date: "Thu Feb 21 2019 11:44:24 GMT+0000 (GMT)" },
    { text: "Lorem 2 ipsum", date: "Thu Feb 21 2019 11:44:24 GMT+0000 (GMT)" },
    { text: "Lorem 3 ipsum", date: "Thu Mar 21 2019 11:44:24 GMT+0000 (GMT)" },
];

let result = {};
data.forEach(entry => {
    let moyr = new Date(entry.date)
        .toLocaleString("en-us", { month: 'long', year: 'numeric' })
    result[moyr] = result[moyr] || { text: [] };
    result[moyr].text.push(entry.text);
});

console.log( result );

const data = [
    { text: "Lorem 1 ipsum", date: "Thu Feb 21 2019 11:44:24 GMT+0000 (GMT)" },
    { text: "Lorem 2 ipsum", date: "Thu Feb 21 2019 11:44:24 GMT+0000 (GMT)" },
    { text: "Lorem 3 ipsum", date: "Thu Mar 21 2019 11:44:24 GMT+0000 (GMT)" },
];

let result = data.reduce( (r,entry) => {
    let moyr = new Date(entry.date)
        .toLocaleString("en-us", { month: 'long', year: 'numeric' })
    r[moyr] = r[moyr] || { text: [] };
    r[moyr].text.push(entry.text);
    return r;
},{})

console.log( result );