How to group an array of objects by key

后端 未结 24 2906
后悔当初
后悔当初 2020-11-21 05:13

Does anyone know of a (lodash if possible too) way to group an array of objects by an object key then create a new array of objects based on the grouping? For example, I hav

24条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 05:39

    I liked @metakunfu answer, but it doesn't provide the expected output exactly. Here's an updated that get rid of "make" in the final JSON payload.

    var cars = [
        {
            'make': 'audi',
            'model': 'r8',
            'year': '2012'
        }, {
            'make': 'audi',
            'model': 'rs5',
            'year': '2013'
        }, {
            'make': 'ford',
            'model': 'mustang',
            'year': '2012'
        }, {
            'make': 'ford',
            'model': 'fusion',
            'year': '2015'
        }, {
            'make': 'kia',
            'model': 'optima',
            'year': '2012'
        },
    ];
    
    result = cars.reduce((h, car) => Object.assign(h, { [car.make]:( h[car.make] || [] ).concat({model: car.model, year: car.year}) }), {})
    
    console.log(JSON.stringify(result));
    

    Output:

    {  
       "audi":[  
          {  
             "model":"r8",
             "year":"2012"
          },
          {  
             "model":"rs5",
             "year":"2013"
          }
       ],
       "ford":[  
          {  
             "model":"mustang",
             "year":"2012"
          },
          {  
             "model":"fusion",
             "year":"2015"
          }
       ],
       "kia":[  
          {  
             "model":"optima",
             "year":"2012"
          }
       ]
    }
    

提交回复
热议问题