Hes*_*loo 6 javascript arrays sorting collections reactjs
我试图创建一个这样的集合,以便在反应组件中使用:
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},
...
]
},
]
Run Code Online (Sandbox Code Playgroud)
我已经按照以下方式对数据进行排序:
let rawData = [
{ name : 'Animals', id : 10},
{ name : 'Batteries', id : 7},
{ name : 'Baggage', id : 12 },
{ name : 'Cake', id : 7},
...
]
Run Code Online (Sandbox Code Playgroud)
此外,我用这个排序方法,但问题是,它返回一个对象有A,B,C与孩子值的键.但我必须把它变成像上面那样的数组才能使用它.
这是我到目前为止所尝试的:
let data = rawData.reduce(function(prevVal, newVal){
char = newVal.name[0].toUpperCase();
return { group: char, children :{name : newVal.name, id : newVal.id}};
},[])
Run Code Online (Sandbox Code Playgroud)
Nen*_*car 13
您可以reduce使用Object.values该对象创建对象,然后使用该对象.
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)Run Code Online (Sandbox Code Playgroud)