function groupItemsByName(array) {
// create a groups to store your new items
const groups = {};
//loop through your array
array.forEach(obj => {
// destructure each object into name and the rest
const { name, ...rest } = obj;
// if the named group doesnt exist create that name with an empty array
if (!groups[name]) {
groups[name] = { name, items: [] };
}
// add the items to the named group based on the name
groups[name].items.push(rest);
});
return Object.values(groups);
}
const transformedArray = groupItemsByName(inputArray);
function groupItemsByName(array) {
//Object.values returns an objects values as an array
return Object.values(
array.reduce((groups, obj) => {
// destructure as in the forEach method
const { name, ...rest } = obj;
// create the groups like in the previous method
groups[name] = groups[name] || { name, items: [] };
// push the items to the group based on the name
groups[name].items.push(rest);
return groups;
}, {})
);
}
const transformedArray = groupItemsByName(inputArray);
您可以使用Object.values 與 Array.prototype.reduce 結合() 和 Array.prototype .push()
#程式碼:
你不需要lodash,你可以只使用JavaScript
使用forEach#
使用減少和Object.values()
使用地圖和減少
#輸出