Home >Web Front-end >JS Tutorial >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 })); }
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"));
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!