【问题标题】:Reduce JavaScript Objects into Array of Formatted Objects将 JavaScript 对象减少为格式化对象数组
【发布时间】: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


    【解决方案1】:

    看看这个方法

    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
    }

    【讨论】:

    • 酷,感谢您的回复!我其实不知道 Array.find()
    • @KurtPetrek 是的,我认为我们可以避免 find,因为它是 O(n^2),所以,用 O(n) 解决方案查看更新的答案。
    猜你喜欢
    • 2021-04-02
    • 1970-01-01
    • 2017-08-17
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多