我有很多生日
const birthdays = [
{name: 'John', birthday: '08-08-1960'},
{name: 'James', birthday: '08-25-1960'},
{name: 'Mary', birthday: '01-01-1990'},
]
,我需要生成一个新数组,其生日按 month-year
分组const grouped = [
{'08-1960': [
{name: 'John', birthday: '08-08-1960'},
{name: 'James', birthday: '08-25-1960'},
]},
{'01-1990': [
{name: 'Mary', birthday: '01-01-1990'},
]},
]
我正在看这样的东西。使用 moment 和 lodash
let groupedResults = _.groupBy(results, (result) => moment(result['Date'], 'DD/MM/YYYY').startOf('isoWeek'));
但是我无法想象如何生成新的数组结构(以年月为键)谢谢。
更新:它应该返回一个数组,而不是一个对象:facepalm
答案 0 :(得分:4)
您可以使用reduce()
reduce()
并将累加器设置为空对象{}
split()
前-
生日,只获得第一个和第三个元素。concat()
个新值累加。否则concat()
将其设置为空数组[]
,然后将其设置为累加器的属性。
const arr = [
{name: 'John', birthday: '08-08-1960'},
{name: 'James', birthday: '08-25-1960'},
{name: 'John', birthday: '01-01-1990'},
]
let res = arr.reduce((ac,a) => {
let key = a.birthday.split('-');
key = `${key[0]}-${key[2]}`;
ac[key] = (ac[key] || []).concat(a);
return ac;
},{})
res = Object.entries(res).map(([k,v]) => ({[k]:v}))
console.log(res)
答案 1 :(得分:0)
如此处https://www.dyn-web.com/javascript/arrays/associative.php所述,您可以创建索引为字符串的数组,但是我不能像普通数组那样工作。
这是您要执行的操作的摘要。
const birthdays = [
{name: 'John', birthday: '08-08-1960'},
{name: 'James', birthday: '08-25-1960'},
{name: 'Mary', birthday: '01-01-1990'},
];
const grouped = birthdays.reduce((prev, cur) => {
const date = new Date(cur.birthday);
const key = `${(date.getMonth() + 1)}-${date.getFullYear()}`;
if(!prev[key]){
prev[key] = [ cur ];
}
else{
prev[key].push(cur);
}
return prev;
}, []);
for(let i in grouped){
console.log(grouped[i]);
}