3 回答
TA贡献1788条经验 获得超4个赞
您可以累积到一个新的对象字面量,而不是通过将每个对象连接到一个新数组来累积到一个数组。您可以通过将累积的对象传播到新的对象文字中来做到这一点。然后,再次,您可以为当前对象团队传播累积对象的结果,或者|| {}如果一个不存在,则采用默认对象 ( )。最后,您可以在嵌套对象文字上设置一个新键,obj.key并将其值设置为当前迭代对象本身。
const data = [
{ team:"sales", key:"employees", value:24 },
{ team:"sales", key:"floor", value:2 },
{ team:"finance", key:"employees", value:7 },
{ team:"finance", key:"floor", value:2 },
];
const groupBy = (array, field) => array.reduce((acc, obj) =>
({...acc, [obj[field]]: {...(acc[obj[field]] || {}), [obj.key]: obj}}), {});
console.log(groupBy(data,'team'));
TA贡献1890条经验 获得超9个赞
您可以通过检查和添加新对象或最后一个键从数据中获取对象来获取用于分组和减少对象的键数组。
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 }],
groups = ['team', 'key'],
result = d.reduce((acc, obj) => {
groups.reduce((o, key, i, { length }) => {
const k = obj[key];
return o[k] = o[k] || (i + 1 === length ? obj : {});
}, acc);
return acc;
}, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
TA贡献1793条经验 获得超6个赞
您可以使用减少
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 },]
let groupBy = (data, property) => data.reduce((op, inp) => {
let prop = inp[property]
let key = inp.key
op[prop] = op[prop] || {}
op[prop][key] = op[prop][key] || {}
op[prop][key] = inp
return op
}, {})
console.log(groupBy(d, 'team'))
添加回答
举报