Home > Web Front-end > JS Tutorial > How Can I Efficiently Group Nested Objects by Custom Keys Using Lodash?

How Can I Efficiently Group Nested Objects by Custom Keys Using Lodash?

Patricia Arquette
Release: 2024-12-08 07:12:12
Original
982 people have browsed it

How Can I Efficiently Group Nested Objects by Custom Keys Using Lodash?

Grouping Nested Objects by Custom Keys

To facilitate rendering, an array of objects must be transformed to group objects with specific key names. The objective is to create an output where the objects are grouped by these designated keys, as seen below:

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

Implementation Approach

This transformation can be achieved by combining Lodash functions _.map and _.groupBy.

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

The groupAndMap function takes four parameters:

  • items: The array of objects to be grouped.
  • itemKey: The key to group the items by.
  • childKey: The key to use for the nested groups.
  • predic: An optional predicate to apply to the nested groups.

The function first groups the items by the itemKey using _.groupBy. Then, it iterates over the grouped objects and creates a new object with the itemKey and childKey. If the predic parameter is provided, it applies the predicate to the nested groups.

Example Usage

To use this function to group the given objects, call it as follows:

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

This will group the items by the "tab" and "section" keys, resulting in the desired output.

The above is the detailed content of How Can I Efficiently Group Nested Objects by Custom Keys 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