为了账号安全,请及时绑定邮箱和手机立即绑定

JavaScript ES6:对象数组到数组按键分组并按属性索引

JavaScript ES6:对象数组到数组按键分组并按属性索引

犯罪嫌疑人X 2022-06-09 16:17:36
我有一个对象数组。简化版(只有几个属性):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团队内部的级别分组。
查看完整描述

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'));


查看完整回答
反对 回复 2022-06-09
?
当年话下

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


查看完整回答
反对 回复 2022-06-09
?
摇曳的蔷薇

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'))


查看完整回答
反对 回复 2022-06-09
  • 3 回答
  • 0 关注
  • 390 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信