I have an array of objects in the format
{type: number, sub_type: number}
I need to sort them into an array of objects formatted like this
{
type_id: (type from at least one object in array above),
sub_types: [
(all sub types from objects in array above that match this type)
]
}
This is what I came up but I think there is a more efficient way. rawTypes
is an array of objects in need of formatting, types
ends up being the array of formatted objects.
const typeIds = [...new Set(rawTypes.map(val => val.type))];
const types = typeIds.map(val => ({type_id: val, sub_types: [] }));
rawTypes.forEach(obj => {
let typeIndex = types.reduce((accum, val, i) => val.type_id === obj.type ? i : accum, 0);
types[typeIndex].sub_types.push(obj.sub_type);
});
I think a better solution would use recursion but I can't think of how to do it.
var data = [{type: 5, sub_type: 10}, {type: 5, sub_type: 11}, {type: 6, sub_type: 12}]; var obj = data.reduce((a, c) => { var current = a[`type_id_${c.type}`]; if (current) { current.sub_types.push(c.sub_type); } else { var key = `type_id_${c.type}`; a = { ...a, ...{ [key]: {sub_types: [c.sub_type], 'key': c.type} } }; } return a; }, {}); var array = Object.keys(obj).map((k) => ({ 'type': obj[k].key, 'subtypes': obj[k].sub_types })); console.log(array)
.as-console-wrapper { max-height: 100% !important }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.