javascript | Object grouping

后端 未结 10 1278
不思量自难忘°
不思量自难忘° 2020-11-27 05:29

I have an object. It looks like below:

[
  {
    \"name\":\"Display\",
    \"group\":\"Technical detals\",
    \"id\":\"60\",
    \"value\":\"4\"
  },
  {
           


        
10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 06:22

    Use reduce and filter.

    lets say your initial array is assigned to data

    data.reduce((acc, d) => {
        if (Object.keys(acc).includes(d.group)) return acc;
    
        acc[d.group] = data.filter(g => g.group === d.group); 
        return acc;
    }, {})
    

    this will give you something like

    {
        "Technical detals" = [
        {
           'group'   = 'Technical detals',
           'name'    = 'Display',
           'id'      = '60',
           'value'   = '4'
        },
        {
           'group'   = 'Technical detals',
           'name'    = 'OS',
           'id'      = '37',
           'value'   = 'Apple iOS'
        }],
        "Manufacturer"   = [
        {
           'group'   = 'Manufacturer',
           'name'    = 'Manufacturer',
           'id'      = '58',
           'value'   = 'Apple'
        }]
    }
    

提交回复
热议问题