简体   繁体   中英

Objects of array Group by object key

I have done a number of iterations but haven't achieved by expectation. I have array of Object like one pair below

 const data = [
       {
            "credit_account_id": "244",
            "debit_account_id": null,
            "sum": "30.00",
            "name": "Bank"
        },
        {
            "credit_account_id": null,
            "debit_account_id": "244",
            "sum": "110.00",
            "name": "Bank"
        },

         ....
    ]

i want to achieve

[
    {   name: "Bank",
        account : "244",
        debit_account : "30",
        credit_account: 110
    }
]
const data = [
       {
            "credit_account_id": "244",
            "debit_account_id": null,
            "sum": "30.00",
            "name": "Bank"
        },
        {
            "credit_account_id": null,
            "debit_account_id": "244",
            "sum": "110.00",
            "name": "Bank"
        }

    ]

    
    const dd = [];
            data.map((d) => {
              const item = dd.find((x) => x.name === d.name);
              if (item) {
                if (d.debit_account_id) {
                  item.debit_account = d.sum;
                }
                return (item.credit_account = d.sum);
              }
              const obj = { name: d.name };
              if (d.debit_account_id) {
                obj.debit_account = d.sum;
                obj.ledger_account = d.debit_account_id;
              } else {
                obj.credit_account = d.sum;
                obj.ledger_account = d.credit_account_id;
              }
              return dd.push(obj);
            });

console.log(dd)

 [
        {   name: "Bank",
            account : "244",
            debit_account : "30",
            credit_account: 110
        }
    ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM