Home >Web Front-end >JS Tutorial >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: [ { ... }, { ... } ], }, }, ... ]
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 })); }
The groupAndMap function takes four parameters:
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"));
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!