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

How Can I Efficiently Group an Array of Objects by Nested Keys Using Lodash?

Mary-Kate Olsen
Release: 2024-12-07 06:13:12
Original
540 people have browsed it

How Can I Efficiently Group an Array of Objects by Nested Keys Using Lodash?

Grouping an Array of Objects by Nesting Keys with Specific Names

This query seeks to modify an array of objects by grouping them based on specific key names, yielding a desired output with nested objects.

To accomplish this, a custom function called groupAndMap is employed. It utilizes a combination of _.map and _.groupBy from the Lodash library. Here's a breakdown of how it works:

function groupAndMap(items, itemKey, childKey, predic){
    return _.map(_.groupBy(items,itemKey), (obj,key) => ({
        [itemKey]: key,
        [childKey]: (predic && predic(obj)) || obj
    }));
}
Copy after login
  • The function takes four parameters: items (the array to group), itemKey (the key to group by), childKey (the property name of the nested object), and predic (an optional predicate function that can be used to modify the nested objects).
  • It applies _.groupBy to the items array using the itemKey, grouping the objects into arrays based on their itemKey.
  • Using _.map, each object in the grouped array is converted into a new object with two properties: [itemKey] and [childKey].
  • The predic parameter, if provided, allows for further customization of the nested objects. It is applied to the array of objects for each itemKey before assigning it to the [childKey] property.

To create the desired nested output, the function is used twice in the code snippet:

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

The first call groups the objects by the "tab" key, resulting in an array of objects with the "tab" and "sections" properties. The zweite call then groups the objects within each section by the "section" key, yielding the desired nested output where objects are grouped by "tab" and then by "section".

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