JavaScript:如何对嵌套数组进行分组 [英] JavaScript: How to group nested array
问题描述
我试图在React Native中使用SectionList显示数据.我已经在下面的代码中显示了我要完成的工作.
I am trying to display data using SectionList in React Native. I have written the code below displaying what I am trying to accomplish.
我希望首先将数据按 date
分组在一起,然后在该日期之内,我需要将它们按位置分组.常规的JavaScript解决方案将起作用.重要的是,它具有 title
和 data
键.
I want the data to first be grouped together by date
, and inside of that date, I need them grouped by location. A regular JavaScript solution will work. It's important that it has a title
and data
key.
我的输入数据采用以下格式:
My input data is in this format:
[ { game_id: 1171,
date: '2018-11-17',
location: 'Plaza'
},
{ game_id: 1189,
date: '2018-11-17',
location: 'Field - Kickball'
},
{ game_id: 1489,
date: '2018-11-16',
location: 'Field - Kickball'
},
{ game_id: 1488,
date: '2018-11-16',
location: 'Field - Soccer'
}
]
我需要从上面的数据数组中获得以下输出:
I need the obtain the following output from the data array above:
data = [{
title: "2018-11-17",
data: [{
title: "Field - Kickball",
data: [{
game_id: 1189,
date: '2018-11-17',
location: 'Field - Kickball'
}]
},
{
title: "Plaza",
data: [{
game_id: 1171,
date: '2018-11-17',
location: 'Plaza'
}]
}
]
},
{
title: "2018-11-16",
data: [{
title: "Field - Kickball",
data: [{
game_id: 1489,
date: '2018-11-16',
location: 'Field - Kickball'
}]
},
{
title: "Field - Soccer",
data: [{
game_id: 1488,
date: '2018-11-16',
location: 'Field - Soccer'
}]
}
]
}
]
我已经尝试过了:
const games = [data here]
var groups = _(games)
.groupBy(x => x.date)
.map(value => {
return _.groupBy(value, 'location')
.map(({key, value}) => ({title: key, data: value}))
})
.map((value, key) => {
return ({title: value[Object.keys(value)[0]][0].date, data: value})
})
推荐答案
如果要使用标准解决方案,则可以先缩小为一个对象,然后返回该对象的值,然后再次在输出中进行分组:)
If you want a standard solution, then you could first reduce to an object, and return the values of that object, and then group again on the output :)
function groupBy( arr, prop ) {
return Object.values( arr.reduce( ( aggregate, item ) => {
const val = item[prop];
if (!aggregate[val]) {
aggregate[val] = {
[prop]: val,
data: []
};
}
aggregate[val].data.push( item );
return aggregate;
}, {} ) );
}
const games = [ { game_id: 1171,
date: '2018-11-17',
location: 'Plaza'
},
{ game_id: 1189,
date: '2018-11-17',
location: 'Field - Kickball'
},
{ game_id: 1489,
date: '2018-11-16',
location: 'Field - Kickball'
},
{ game_id: 1488,
date: '2018-11-16',
location: 'Field - Soccer'
}
];
const grouped = groupBy( games, 'date' )
.map( item => ({ ...item, data: groupBy( item.data, 'location' ) }) );
console.log( grouped );
请注意,我只是使用提取的道具作为分组的目标属性,如果您想使用 title
,只需将 [prop]:val
更改为'title':val
,然后您就可以使第二个分组更容易了:)
Note that I just use the prop that got extracted as a target property for the grouping, if you want title
instead, just change the [prop]: val
to 'title': val
and then you can make your second grouping a litle bit easier :)
这篇关于JavaScript:如何对嵌套数组进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!