简体   繁体   English

lodash .groupBy。 如何为分组输出添加自己的密钥?

[英]lodash .groupBy. how to add your own keys for grouped output?

[{
    "car_brand": "audi",
    "model": {
      "model_1": "audi_tt"
    }

  },
  {
    "car_brand": "audi",
    "model": {
      "model_1": "audi_r8"
    }
  }
]

anyways convert to as be无论如何转换为

[{
  "car_brand": "audi",
  "model": [{
      "model_1": "audi_tt"
    },
    {
      "model_1": "audi_r8"
    }
  ]
}]

You can first use _.groupBy() to group each object, and then _.map() each group in the object to an array of objects.可以先使用_.groupBy()对每个对象进行分组,然后_.map()将对象中的每个组都转换为一个对象数组。 Each mapped object uses the key from the grouped object as the car_brand , as well as uses a mapped version of the grouped value array as the model property:每个映射对象使用分组对象中的键作为car_brand ,并使用分组值数组的映射版本作为model属性:

 const arr = [{ "car_brand": "audi", "model": { "model_1": "audi_tt" } }, { "car_brand": "audi", "model": { "model_1": "audi_r8" } } ]; const group = _.flow( inp => _.groupBy(inp, 'car_brand'), gr => _.map(gr, (arr, card_brand) => ({ card_brand, model: _.map(arr, 'model') })) ); console.log(group(arr));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM