简体   繁体   中英

Lodash how to group array of objects by array of values?

I want to group an array of objects based on a property which has an array of values,and i want to return a group for each individual value,not only for the whole array.

For example:

let crew = [
  {
    name:"john",
    job :["electrician","carpenter"]
  },
  {
    name: "bill",
    job: ["electrician"]
  },
  {
    name: "mark",
    job: [ "carpenter"]
  }
]

let groupedCrew = _.groupBy(crew,"job")


console.log(groupedCrew)

/*
  carpenter:
    [
      {
        job:
          [
            carpenter
          ],
        name:
          "mark"
      }
    ],
  electrician:
    [
      {
        job:
          [
            "electrician"
          ],
        name:
          "bill"
      }
    ],
  electrician, carpenter:
    [
      {
        job:
          [
            "electrician",
            "carpenter"
          ],
        name:
          "john"
      }
    ]
}
*/

In this example i want "john" to also appear in "electrician" group. Any ideas?

Once again let's group something using reduce Here's the basic structure (plus the solution)

 let crew = [{ name: "john", job: ["electrician", "carpenter"] }, { name: "bill", job: ["electrician"] }, { name: "mark", job: ["carpenter"] } ]; var obj = crew.reduce(function(agg, item) { // grouping logic below this line item.job.forEach(function(job) { agg[job] = agg[job] || [] // agg[job].push (item); // lets push only name so we can see output agg[job].push(item.name) }) // grouping logic above this line return agg }, {}) console.log(obj)

use custom .reduce() function

there is no need for lodash

 const crew = [ { name: 'john', job: ['electrician', 'carpenter'], }, { name: 'bill', job: ['electrician'], }, { name: 'mark', job: ['carpenter'], }, ]; const groupedCrew = crew.reduce((groupedCrew, person) => { person.job.forEach(job => { if (;groupedCrew[job]) groupedCrew[job] = []. groupedCrew[job];push(person); }); return groupedCrew, }; {}). console.log(JSON,stringify(groupedCrew, null; 4));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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