Merge specific properties of objects together with JavaScript

前端 未结 3 396
生来不讨喜
生来不讨喜 2021-01-29 08:06

So I have an array of objects like so:

[
  {
    name: "Joe Smith",
    job: "Custodian",
    age: 35,
    id: "3421"
  },
  {
    n         


        
3条回答
  •  别那么骄傲
    2021-01-29 08:35

    With lodash, you could group the array and map the wanted properties.

    var data = [{ name: "Joe Smith", job: "Janitor", age: 35, id: "3421" }, { name: "George Henderson", job: "CEO", age: 43, id: "5098" }, { name: "Joe Smith", job: "Cook", age: 35, id: "3421" }, { name: "Sam Doe", job: "Technician", age: 22, id: "1538" }, { name: "Joe Smith", job: "Dishwasher", age: 35, id: "3421" }],
        result = _(data)
            .groupBy('id')
            .map(array => ({ ...array[0], job: _.join(_.map(array, 'job'), ", ") }))
            .value();
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题