【发布时间】:2018-07-18 11:30:56
【问题描述】:
我有一个格式为对象的数组
{type: number, sub_type: number}
我需要将它们分类成这样格式的对象数组
{
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)
]
}
这是我想出的,但我认为有一种更有效的方法。 rawTypes 是需要格式化的对象数组,types 最终是格式化对象的数组。
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);
});
我认为更好的解决方案是使用递归,但我想不出该怎么做。
【问题讨论】:
标签: javascript arrays recursion formatting javascript-objects