我有一个对象数组。简化版(只有几个属性):
let d = [
{ team:"sales", key:"employees", value:24 },
{ team:"sales", key:"floor", value:2 },
{ team:"finance", key:"employees", value:7 },
{ team:"finance", key:"floor", value:2 },
]
想要使用普通 (ES6) JavaScript 进行分组team,然后按key:
{
sales: {
employees: { team:"sales", key:"employees", value:24 },
floor: { team:"sales", key:"floor", value:2 }
},
finance: {
employees: { team:"finance", key:"employees", value:7 },
floor: { team:"finance", key:"floor", value:2 }
}
}
与其他问题有些相似,但不完全一样。
到目前为止我所拥有的:使用 reduce 来分组team:
let groupBy = (data, field) => data.reduce((acc, obj) => Object.assign(acc, { [obj[field]]:( acc[obj[field]] || [] ).concat(obj) }), {})
let result = groupBy(d,'team')
这给出了:
{
sales: [
{ team:"sales", key:"employees", value:24 },
{ team:"sales", key:"floor", value:2 }
],
finance: [
{ team:"finance", key:"employees", value:7 },
{ team:"finance", key:"floor", value:2 }
]
}
不确定推荐的方法是按key团队内部的级别分组。
尚方宝剑之说
当年话下
摇曳的蔷薇
索引数组的键取值
数组属性length
JavaScript 难不成只有索引数组,没有关联数组?
PHP数组
相关分类