我有一个包含日期的简单对象列表,我需要按日期对它们进行分组。 不幸的是,它似乎无法发挥作用。
以下是简化代码:
games = [
{date:"3/5/17", name:"game 1, 3"},
{date:"3/5/17", name:"game 2, 3"},
{date:"4/5/17", name:"game 3, 4"},
{date:"4/5/17", name:"game 4, 4"},
{date:"4/5/17", name:"game 5, 4"},
{date:"5/5/17", name:"game 6, 5"},
{date:"5/5/17", name:"game 7, 5"},
]
let games_by_date = []
games.map( (i)=>{
if(!games_by_date[i['date']])
games_by_date[i['date']]=[];
games_by_date[i['date']].push(i);
} )
console.log(games_by_date) // shows [3/5/17: Array[2], 4/5/17: Array[3], 5/5/17: Array[2]], but shows it as Array[0]
console.log(games_by_date[0]) // undefined
console.log(games_by_date[1]) // undefined
games_by_date.map( (g)=>console.log(g) ) // doesn't even gets there
如果我这样做但使用不同的列,它就能正常工作。
games = [
{date:"3/5/17", day:"3", name:"game 1, 3"},
{date:"3/5/17", day:"3", name:"game 2, 3"},
{date:"4/5/17", day:"4", name:"game 3, 4"},
{date:"4/5/17", day:"4", name:"game 4, 4"},
{date:"4/5/17", day:"4", name:"game 5, 4"},
{date:"5/5/17", day:"5", name:"game 6, 5"},
{date:"5/5/17", day:"5", name:"game 7, 5"},
]
let games_by_date = []
games.map( (i)=>{
if(!games_by_date[i['date']])
games_by_date[i['date']]=[];
games_by_date[i['date']].push(i);
} )
console.log(games_by_date)
console.log(games_by_date[0])
console.log(games_by_date[1])
games_by_date.map( (g, d)=>console.log(d, g) )
console.log("--------------------")
let games_by_day = []
games.map( (i)=>{
if(!games_by_day[i['day']])
games_by_day[i['day']]=[];
games_by_day[i['day']].push(i);
} )
console.log(games_by_day)
console.log(games_by_day[0])
console.log(games_by_day[1])
games_by_day.map( (g, d)=>console.log(d, g) )

所以它似乎因为我使用的键的类型而发生。
你遇到过它,你是怎么解决的? 感谢
答案 0 :(得分:3)
您可以使用reduce来按键分组:
let games = [
{date:"3/5/17", name:"game 1, 3"},
{date:"3/5/17", name:"game 2, 3"},
{date:"4/5/17", name:"game 3, 4"},
{date:"4/5/17", name:"game 4, 4"},
{date:"4/5/17", name:"game 5, 4"},
{date:"5/5/17", name:"game 6, 5"},
{date:"5/5/17", name:"game 7, 5"},
];
let games_by_date = games.reduce((a,b) => {
a[b.date] = a[b.date] ? a[b.date].concat(b) : [b];
return a;
}, {});
console.log(games_by_date);
因为“日期”只是字符串,所以它们应该没有问题。
正如@Liam指出的那样,这将创建一个对象而不是数组,有关此内容的完整说明,请参阅@Liam's answer。
答案 1 :(得分:2)
您的games_by_date
数组应该是一个能够按日期键入的对象。 day
键自动转换为整数,因为它们是整数形式,因此可以用作数组中的键。但是,要使用日期字符串,您必须更改var games_by_date = {}
并且它应该可以正常工作。
请注意,您不能.map
常规JavaScript中的对象。但是,您可以使用for (i in games_by_date)
循环键,或使用lodash
提供_.map(object, callback)
。