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

我有一个对象数组。简化版(只有几个属性):


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团队内部的级别分组。


犯罪嫌疑人X
浏览 391回答 3
3回答

尚方宝剑之说

您可以累积到一个新的对象字面量,而不是通过将每个对象连接到一个新数组来累积到一个数组。您可以通过将累积的对象传播到新的对象文字中来做到这一点。然后,再次,您可以为当前对象团队传播累积对象的结果,或者|| {}如果一个不存在,则采用默认对象 ( )。最后,您可以在嵌套对象文字上设置一个新键,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'));

当年话下

您可以通过检查和添加新对象或最后一个键从数据中获取对象来获取用于分组和减少对象的键数组。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; }

摇曳的蔷薇

您可以使用减少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'))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript