且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按首字母顺序按字母顺序对对象进行排序和分组

更新时间:2023-11-30 09:39:04

您可以使用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)