【问题标题】:Sort and group objects alphabetically by first letter Javascript按首字母 Javascript 按字母顺序对对象进行排序和分组
【发布时间】:2018-12-03 04:19:27
【问题描述】:

我试图创建一个这样的集合以便在反应组件中使用:

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}};
},[])

【问题讨论】:

    标签: javascript arrays reactjs sorting collections


    【解决方案1】:

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

    【讨论】:

    • 嗨@NenadVracar,你能解释一下吗?在此先感谢...
    • @Gerben den Boer 更新了答案。
    • @NenadVracar 我认为这不会按字母顺序对对象进行排序?还是我错过了什么
    • 首先,您需要按名称对数据进行排序。 let data = rawData.sort((a, b) => a.name.localeCompare(b.name, 'es', {sensitive: 'base' })).reduce(...
    • 在打字稿上我得到Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'.ts(7053) for r[group]
    猜你喜欢
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 2021-02-18
    相关资源
    最近更新 更多