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', } ];
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: [ { ... }, { ... } ], }, }, ... ]
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"));
The result variable now contains the desired grouped array of objects:
console.log(result);
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!