Problem:
Given an array of objects, the task is to reorganize them into a format optimized for rendering by creating nested structures based on specific key values.
Example:
Input Array:
[ { 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', } ]
Desired Output:
[ { tab: 'Results', sections: [ { section: '2017', items: [ { 'item that belongs here' }, { ... } ] } ] }, { tab: 'Reports', sections: [ { section: 'Marketing', items: [ { ... }, { ... } ] } ] } ]
Solution:
This transformation can be achieved using a combination of 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 })); }
To nest the data as desired, apply groupAndMap recursively.
const output = groupAndMap(items, "tab", "sections", arr => groupAndMap(arr, "section", "items") );
This solution accomplishes the objective of grouping and nesting the array of objects based on specific key values.
The above is the detailed content of How to Nest an Array of Objects Based on Key Values for Optimized Rendering?. For more information, please follow other related articles on the PHP Chinese website!