使用lodash将对象分组

时间:2018-11-19 12:11:21

标签: javascript lodash

我有一个数组add-on

userList

我希望它像:

[
  {email : 'abc@gmail.com',
  department : 'd1'},
  {email : 'abc@gmail.com',
  department : 'd2'},
  {email : 'dec@gmail.com',
  department : 'd1'},
]

我使用以下方法实现了它:

[
  {
  email : 'abc@gmail.com',
  department : ['d1','d2']
  },
  {
  email : 'dec@gmail.com',
  department : ['d1']
  }
]

如何使用const userGrp = _.groupBy(userList, 'email'); let data = []; for (let key in userGrp) { if (userGrp.hasOwnProperty(key)) { const obj = { email: key, dept: extractDept(userGrp[key]), }; data.push(obj); } } function extractDept(userObjList) { const arr = []; userObjList.forEach((element) => { arr.push(element.departmentName); }); return arr; } 来实现?

3 个答案:

答案 0 :(得分:2)

由于使用普通js非常容易,因此这是普通js的分组方式

const grouped = [...foo.reduce((a, {email, department}) =>
     a.set(email, (a.get(email) || []).concat(department))
, new Map)].map(([email, department]) => ({email, department}));

console.log(grouped)
<script>
const foo = [
    {email : 'abc@gmail.com',
        department : 'd1'},
    {email : 'abc@gmail.com',
        department : 'd2'},
    {email : 'dec@gmail.com',
        department : 'd1'},
];

</script>

答案 1 :(得分:0)

这是Lodash的一个有效示例:http://jsfiddle.net/houssein/u4dzLk2b/1/

   var data = [
      {email : 'abc@gmail.com',
      department : 'd1'},
      {email : 'abc@gmail.com',
      department : 'd2'},
      {email : 'dec@gmail.com',
      department : 'd1'},
    ];

    var result = _.chain(data)
        .groupBy("email")
        .pairs()
        .map(function (currentItem) {
            return _.object(_.zip(["email", "departement"], currentItem));
        })
        .value();
    console.log(result);

答案 2 :(得分:0)

email上使用Lodash分组,并使用条目和“映射”来获得所需的输出:

const data = [{ email: 'abc@gmail.com', department: 'd1' }, { email: 'abc@gmail.com', department: 'd2' }, { email: 'dec@gmail.com', department: 'd1' }, ]

const result = _(data)
  .groupBy('email')
  .entries()
  .map(([k,v]) => ({email: k, departments: _.map(v, 'department')}))
  .value()

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

使用ES6:

const data = [{ email: 'abc@gmail.com', department: 'd1' }, { email: 'abc@gmail.com', department: 'd2' }, { email: 'dec@gmail.com', department: 'd1' }, ]

const grp = data.reduce((r,c) => (r[c.email] = [...r[c.email] || [], c], r), {})
console.log(Object.entries(grp).map(([k,v]) => 
   ({email: k, departments: v.map(x => x.department)})))