Home > Web Front-end > JS Tutorial > How to Group Multiple Keys in an Array of Objects Using Lodash?

How to Group Multiple Keys in an Array of Objects Using Lodash?

Patricia Arquette
Release: 2024-12-03 03:53:09
Original
979 people have browsed it

How to Group Multiple Keys in an Array of Objects Using Lodash?

Group Multiple Keys in an Array of Objects with Unique Names

The task at hand involves modifying an array of objects to facilitate easier rendering. The goal is to group objects by specific keys, regardless of their actual names in the original array.

Consider the following input array:

const items = [
  {
    tab: 'Results',
    section: '2017',
    title: 'Full year Results',
    description: 'Something here',
  },
  {
    tab: 'Results',
    section: '2017',
    title: 'Half year Results',
    description: 'Something here',
  },
  {
    tab: 'Reports',
    section: 'Marketing',
    title: 'First Report',
    description: 'Something here',
  }
];
Copy after login

Our target output is to have a new array with the following structure:

const output = [
  {
    tab: 'Results',
    sections: [
      {
        section: '2017',
        items: [ { 'item that belongs here' }, { ... } ],
      },
  },
  {
    tab: 'Reports',
    sections: [
      {
        section: 'Marketing',
        items: [ { ... }, { ... } ],
      },
  },
...
]
Copy after login

To achieve this, we can employ a combination of Lodash's _.map and _.groupBy functions:

const groupAndMap = (items, itemKey, childKey, predic) => {
    return _.map(_.groupBy(items, itemKey), (obj, key) => ({
        [itemKey]: key,
        [childKey]: (predic && predic(obj)) || obj
    }));
};

var result = groupAndMap(items, "tab", "sections", 
                arr => groupAndMap(arr, "section", "items"));
Copy after login

The result variable now contains the desired grouped array of objects:

console.log(result);
Copy after login

The above is the detailed content of How to Group Multiple Keys in an Array of Objects Using Lodash?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template