如何转换这两个数据结构?

时间:2019-04-19 04:09:56

标签: javascript arrays object

我怎么能 转换:

[{"year":2019, "title": "title0"}, {"year":2019, "title": "title1"},{"year":2018, "title": "title2"}, {"year":2018, "title": "title3"}]

收件人:

[{"year":2019, "list":["title0", "title1"]}, {"year":2018, "list":["title2", "title3"]}]

使用Javascript?

1 个答案:

答案 0 :(得分:1)

您可以将Object.values()Array.prototype.reduce()结合使用:

const data = [{"year":2019, "title": "title0"}, {"year":2019, "title": "title1"},{"year":2018, "title": "title2"}, {"year":2018, "title": "title3"}];
const result = Object.values(data.reduce((a, {year, title}) => {
  a[year] = a[year] || {year, list: []};
  a[year].list.push(title);
  return a;
}, {}));

console.log(result);