繁体   English   中英

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

[英]Reduce JavaScript Objects into Array of Formatted Objects

我有一个格式的对象数组

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

我认为更好的解决方案将使用递归,但我想不出怎么做。

看这种方法

 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