javascript - 按首字母 Javascript 的字母顺序对对象进行排序和分组

标签 javascript arrays reactjs sorting collections

我正在尝试创建这样的集合以便在 React 组件中使用:

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},
            ...
        ]
    },
]

我已经像这样对我的数据进行了排序:

let rawData = [
    { name : 'Animals', id : 10},
    { name : 'Batteries', id : 7},
    { name : 'Baggage', id : 12 },
    { name : 'Cake', id : 7},
    ...
]

我也用过这个sorting method但问题是,它返回一个对象,其中包含 ABC 键以及子项作为值。但是我必须像上面那样把它变成数组才能使用它。

这是我到目前为止尝试过的:

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

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)

关于javascript - 按首字母 Javascript 的字母顺序对对象进行排序和分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51009090/

相关文章:

Python:在可导航窗口中交互式调查大型数组

c++ - 在C++中初始化2D数组类并将其传递给函数

javascript - 在 javascript 代码中添加一两个 PHP 变量

javascript - 在 Javascript 中生成我的网站的 URL

c++ - 在c++中从文件向数据结构中的变量添加值

javascript - 如果 react prop 深深嵌套在 JSON 对象中,如何传递它?

node.js - 异步初始化 React.js 组件的服务器端渲染策略

javascript - onClick 事件后 React 中的条件渲染不起作用

javascript - CKEditor 不适用于 MAC chrome 和 MAC Safari

javascript - 使用 Ajax 和 PHP 上传图像并返回上传的图像 URL