我正在尝试在 React Native 中使用 SectionList 显示数据。我已经编写了下面的代码来显示我想要完成的事情。
我希望数据首先按 date
分组在一起,在该日期内,我需要按位置分组。常规的 JavaScript 解决方案将起作用。重要的是它有一个 title
和 data
键。
我的输入数据是这种格式:
[ { 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'
}
]
我需要从上面的数据数组中获取以下输出:
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})
})
最佳答案
有几种方法可以实现这一点,但是一种不需要第三方依赖项(如 Underscore 或 Lodash)的简单方法可以使用内置的 Array#reduce() 来实现。方法如下图。
有关此解决方案如何工作的详细信息,请参阅以下代码片段中的文档:
const input = [ { 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' } ];
/* Reduce input data to required nested sub-array structure */
const data = input.reduce((result, item) => {
/* Construct item to be inserted into sub array for this item.date
in resulting data object */
const resultItem = {
title: item.location,
data: [{
game_id: item.game_id,
date: item.date,
location: item.location
}]
};
/* Find existing item in result array with title that matches date */
const resultDateList = result.find(i => i.title === item.date);
if (resultDateList) {
/* If matching sublist found, add constructed item to it's data array */
resultDateList.data.push(resultItem);
} else {
/* If not matching sublist found, add a new one to the result for this item
and pre-populate the data array with new item*/
result.push({
title: item.date,
data: [resultItem]
});
}
return result;
}, [])
console.log(data)
希望对您有所帮助!
关于JavaScript:如何对嵌套数组进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56212466/