简体   繁体   English

将JavaScript对象减少为格式化对象数组

[英]Reduce JavaScript Objects into Array of Formatted Objects

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. 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);
});

I think a better solution would use recursion but I can't think of how to do it. 我认为更好的解决方案将使用递归,但我想不出怎么做。

Look at this approach 看这种方法

 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 } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM