大佬教程收集整理的这篇文章主要介绍了JavaScript 将平面数组转换为嵌套/分组和排序数组,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试在 JavaScript 中将对象数组转换为 '分组' 和排序的输出数组,最好是 ES6 方式(例如使用 .map
、.reduce
等)。
总结:
const data = [
{ section: 'A',item: 'a1',section_order: 2,item_order: 2 },{ section: 'B',item: 'b1',section_order: 1,{ section: 'A',item: 'a2',item_order: 1 },item: 'b2',item_order: 1 }
];
const desiredOutput = [
{
section: 'B',// should come first as section_order = 1
items: [
{ section: 'B',// should come first as item_order = 1
{ section: 'B',// should come second as item_order = 2
]
},{
section: 'A',// should come second as section_order = 2
items: [
{ section: 'A',]
}
];
我看到了一个例子,它让我找到了正确的方向 - 但不完全是想要的输出并且没有满足排序顺序:
const result = data.reduce((accum,currElm) => {
const currSection = currElm['section'];
accum[currSection] = (accum[currSection] || []).concat(currElm);
return accum;
},{});
您应该先sort
您的数据。 sort
函数看起来像这样
data.sort((a,b) => (a.section_order - b.section_order) || (a.item_order - b.item_order));
如您所见,我们将条件分为两部分:
(a.section_order - b.section_order)
(a.item_order - b.item_order)
这意味着您对 section_order
然后按 item_order
进行排序。
之后,您可以使用字典功能如下所示循环一次
const data = [
{ section: 'A',item: 'a1',section_order: 2,item_order: 2 },{ section: 'B',item: 'b1',section_order: 1,{ section: 'A',item: 'a2',item_order: 1 },item: 'b2',item_order: 1 }
];
data.sort((a,b) => (a.section_order - b.section_order) || (a.item_order - b.item_order));
var result = [];
for(var item of data){
var section = item.section;
if(!result[section]){ // if not exists => create new
result[section] = { section,items:[item] };
}else{ // if exists => add one more item into items
result[section].items.push(item);
}
}
console.log(Object.values(result));
旧版本使用 reduce & map
@H_616_86@
const data = [
{ section: 'A',b) => (a.section_order - b.section_order) || (a.item_order - b.item_order));
const accumData = data.reduce((accum,currElm) => {
const currSection = currElm['section'];
accum[currSection] = (accum[currSection] || []).concat(currElm);
return accum;
},{});
var result = Object.entries(accumData).map(([key,value]) => ({section: key,items: value}));
console.log(result);
以上是大佬教程为你收集整理的JavaScript 将平面数组转换为嵌套/分组和排序数组全部内容,希望文章能够帮你解决JavaScript 将平面数组转换为嵌套/分组和排序数组所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。