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

如何在Javascript中使用其对象键对数组进行分组

如何在Javascript中使用其对象键对数组进行分组

繁星coding 2022-10-21 14:58:25
我有一个包含员工详细信息和工资信息的数组。我想将员工工资详细信息与员工 ID 分组。这是输入数组:let employeeDetails = [{  "employeeDetail": {    "empID": "XXYYZZ11",    "firstname": "abc",    "joinedAt": "13/04/2014",    "address": "VVGGHHNN"  },  "employeeSalaryDetails": [{    "month": "Jan",    "salaryAmount": "35000",    "Bank": "XXXXX",    "PfAccnum": "XXAAQQWWWWQ"  }]}, {  "employeeDetails": [{    "empID": "XXYYZZ11",    "firstname": "abc",    "joinedAt": "13/04/2014",    "address": "VVGGHHNN"  }],  "employeeSalaryDetails": [{    "month": "Feb",    "salaryAmount": "35000",    "Bank": "XXXXX",    "PfAccnum": "XXAAQQWWWWQ"  }]}]这是我想要实现的输出:let employeeDetails = [{  "employeeDetails": [{    "empID": "XXYYZZ11",    "firstname": "abc",    "joinedAt": "13/04/2014",    "address": "VVGGHHNN"  }],  "employeeSalaryDetails": [{    "month": "Jan",    "salaryAmount": "35000",    "Bank": "XXXXX",    "PfAccnum": "XXAAQQWWWWQ"  }, {    "month": "Feb",    "salaryAmount": "35000",    "Bank": "XXXXX",    "PfAccnum": "XXAAQQWWWWQ"  }]}]这是我尝试过的,但没有得到我想要的结果。function employeeGroup(empArray, key) {  return empArray.reduce((obj, item) => {    (obj[item[key]] = obj[item[key]] || []).push(item)    return obj  }, {})}employeeGroup(employeeDetails, "empId")我是 Javascript 新手。谁可以帮我这个事 ?
查看完整描述

4 回答

?
慕田峪9158850

TA贡献1794条经验 获得超7个赞

使用解构将第一个数组元素提取为 item,并使用 employeeSalaryDetails 属性。

带有 empID 的对象包含在数组中。您没有推送 meployeeSalaryDetails 对象。此外,您的 empId 应该是 empID。


function employeeGroup(empArray, key) {

  return Object.values(empArray.reduce(

  (obj,{employeeDetails: [item], employeeSalaryDetails}) => {

      (obj[item[key]] = obj[item[key]] ||

       { employeeDetails: item, employeeSalaryDetails:[] })

           .employeeSalaryDetails.push(...employeeSalaryDetails)

      return obj

  }, {}))

}

console.log(

  employeeGroup(employeeDetails, "empID")

)

<script>

  let employeeDetails = [{

    "employeeDetails": [{

      "empID": "XXYYZZ11",

      "firstname": "abc",

      "joinedAt": "13/04/2014",

      "address": "VVGGHHNN"

    }],

    "employeeSalaryDetails": [{

      "month": "Jan",

      "salaryAmount": "35000",

      "Bank": "XXXXX",

      "PfAccnum": "XXAAQQWWWWQ"

    }]

  }, {

    "employeeDetails": [{

      "empID": "XXYYZZ11",

      "firstname": "abc",

      "joinedAt": "13/04/2014",

      "address": "VVGGHHNN"

    }],

    "employeeSalaryDetails": [{

      "month": "Feb",

      "salaryAmount": "35000",

      "Bank": "XXXXX",

      "PfAccnum": "XXAAQQWWWWQ"

    }]

  }]

</script>


查看完整回答
反对 回复 2022-10-21
?
POPMUISE

TA贡献1765条经验 获得超5个赞

您可以使用reduce和 过滤掉您可以使用 和 的重复员工filter记录some。这是一个工作示例。


var employeeDetails = [{ "employeeDetails": [ { "empID":"XXYYZZ11", "firstname": "abc", "joinedAt": "13/04/2014", "address": "VVGGHHNN" } ], "employeeSalaryDetails": [ { "month": "Jan", "salaryAmount": "35000", "Bank": "XXXXX", "PfAccnum": "XXAAQQWWWWQ" } ]}, { "employeeDetails": [ { "empID": "XXYYZZ11", "firstname": "abc", "joinedAt": "13/04/2014", "address": "VVGGHHNN" } ], "employeeSalaryDetails": [ { "month": "Feb", "salaryAmount": "35000", "Bank": "XXXXX", "PfAccnum": "XXAAQQWWWWQ" } ] }];


var result = [employeeDetails.reduce((acc, {employeeDetails, employeeSalaryDetails})=>{

    acc['employeeDetails'] = acc['employeeDetails'] || [];

    employeeDetails = employeeDetails.filter(k=>!acc['employeeDetails'].some(l=>l.empID==k.empID));

    acc['employeeDetails'] = [...acc['employeeDetails'], ...employeeDetails];

    acc['employeeSalaryDetails'] = [...(acc['employeeSalaryDetails'] || []), ...employeeSalaryDetails];

    return acc;

},{})];


console.log(result);


查看完整回答
反对 回复 2022-10-21
?
慕工程0101907

TA贡献1887条经验 获得超5个赞

/**

 * 

 * @param {item[]} arr 

 * @param {(item)=>item[<GroupField>]} g 

 * @returns 

 */

function groupBy ( arr, g ) {

    let len = arr.length

    for ( let i = 0; i < len; i++ ) {

        const a = arr.pop();

        const b = g( a );

        const c = arr.find( e => e.d == b )

        if ( c ) {

            c.e.push( a )

        } else {

            arr.unshift( ( {

                d: g( a ),

                e: [ a ]

            } ) )

        }

    }

    return arr.map( e => ( { [ e.d ]: e.e } ) ).reduce( ( p, c ) => ( { ...p, ...c } ) );

}



const result = groupBy( [

    { name: 'a', group: 1 },

    { name: "b", group: 1 },

    { name: "c", group: 10 }

], ( item ) => item.group );



console.log( result );


查看完整回答
反对 回复 2022-10-21
?
慕的地8271018

TA贡献1796条经验 获得超4个赞

假设您的数组将只包含一个对象,则以下代码将起作用。


    let employeeDetails = [{ "employeeDetails": [{ "empID": "XXYYZZ11", "firstname": "abc", "joinedAt": "13/04/2014", "address": "VVGGHHNN" }], "employeeSalaryDetails": [{ "month": "Jan", "salaryAmount": "35000", "Bank": "XXXXX", "PfAccnum": "XXAAQQWWWWQ" }] }, { "employeeDetails": [{ "empID": "XXYYZZ11", "firstname": "abc", "joinedAt": "13/04/2014", "address": "VVGGHHNN" }], "employeeSalaryDetails": [{ "month": "Feb", "salaryAmount": "35000", "Bank": "XXXXX", "PfAccnum": "XXAAQQWWWWQ" }] }]

    function getEmployeeDetails(id){

        let employeeDetail = {employeeDetails:[],employeeSalaryDetails:[]};

        employeeDetails.forEach(function(eachDetail){

            let ed = eachDetail.employeeDetails[0];

            let es = eachDetail.employeeSalaryDetails[0];

            if(ed.empID == id){

                employeeDetail.employeeDetails = ed;

                employeeDetail.employeeSalaryDetails.push(es);

            }

        });

        return [employeeDetail];

    }

    console.log(getEmployeeDetails("XXYYZZ11"));


查看完整回答
反对 回复 2022-10-21
  • 4 回答
  • 0 关注
  • 104 浏览
慕课专栏
更多

添加回答

举报

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