本文介绍了按首字母顺序按字母顺序对对象进行排序和分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图创建一个这样的集合以便在react组件中使用:
Im trying to create a collection like this in order to use in a react component:
let data = [
{
group : 'A',
children : [
{ name : 'Animals', id : 22 },
...
]
},
{
group : 'B', children : [
{ name : 'Batteries', id : 7},
{ name : 'Baggage', id : 12 },
...
]
},
{
group : 'C', children : [
{ name : 'Cake', id : 7},
...
]
},
]
我已经对数据进行了这样的排序:
I've already sort my data like this :
let rawData = [
{ name : 'Animals', id : 10},
{ name : 'Batteries', id : 7},
{ name : 'Baggage', id : 12 },
{ name : 'Cake', id : 7},
...
]
我也使用了这种排序方法,但问题是,它正在返回一个具有A
,B
,C
键的对象,其子级为值.但是我必须像上面一样将其转换为数组才能使用它.
Also I used this sorting method but the problem is, it's returning an Object with A
, B
, C
keys with children as values. But I have to turn it into array like above in order to use that.
这是我到目前为止所尝试的:
Here is what i've tried so far :
let data = rawData.reduce(function(prevVal, newVal){
char = newVal.name[0].toUpperCase();
return { group: char, children :{name : newVal.name, id : newVal.id}};
},[])
推荐答案
您可以使用reduce
创建对象,然后在该对象上使用Object.values
.
You can create object with reduce
and then use Object.values
on that object.
let rawData = [
{ name : 'Animals', id : 10},
{ name : 'Batteries', id : 7},
{ name : 'Baggage', id : 12 },
{ name : 'Cake', id : 7},
]
let data = rawData.reduce((r, e) => {
// get first letter of name of current element
let group = e.name[0];
// if there is no property in accumulator with this letter create it
if(!r[group]) r[group] = {group, children: [e]}
// if there is push current element to children array for that letter
else r[group].children.push(e);
// return accumulator
return r;
}, {})
// since data at this point is an object, to get array of values
// we use Object.values method
let result = Object.values(data)
console.log(result)
这篇关于按首字母顺序按字母顺序对对象进行排序和分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!