簡體   English   中英

如何基於Javascript中的對象鍵從對象數組添加對象值

[英]How to add object values from an object array based on an object key in Javascript

我想基於另一個對象鍵從對象數組添加一些對象值。 我想知道如何通過普通的Javascript或使用lodash之類的幫助程序庫來實現。

我已經嘗試過使用lodash的_.groupByArray.prototype.reduce() ,但是還沒有使用。 數據如下所示:

{
  "2019-01-04": [
    {
        "payments": [
            {
                "sum": "12",
                "currency": "€"
            }
        ]
    }
  ],

  "2019-01-06": [
    {
        "payments": [
            {
                "sum": "50",
                "currency": "€"
            },
            {
                "sum": "30",
                "currency": "£"
            },
            {
                "sum": "40",
                "currency": "Lek"
            },
            {
                "sum": "2",
                "currency": "£"
            },
            {
                "sum": "60",
                "currency": "£"
            }
        ]
    }
  ]
}

我期望從該日期起sum屬性具有所有相同類型的貨幣的總和的結果:

{
  "2019-01-04": [
    {
        "payments": [
            {
                "sum": "12",
                "currency": "€"
            }
        ]
    }
  ],

  "2019-01-06": [
    {
        "payments": [
            {
                "sum": "50",
                "currency": "€"
            },
            {
                "sum": "92",
                "currency": "£"
            },
            {
                "sum": "40",
                "currency": "Lek"
            }
        ]
    }
  ]
}
const result = {};
Object.keys(input).forEach(date => {
    result[date] = [{ }];
    result[date][0].payments = input[date][0].payments.reduce((payments, c) => {
        const grp = payments.find(p => p.currency === c.currency);
        grp ? grp.sum = +grp.sum + +c.sum : payments.push(c);
        return payments;
    }, []);
});

給定您提供的數據結構,使用以下方法將提供所需的輸出:

function sumByCurrency(history) {
    _.forOwn(history, value => {
        const newPayments = [];

        _.forEach(value["0"].payments, v => {
            let existingPayment = _.find(
                newPayments,
                newPayment => newPayment && newPayment.currency === v.currency
            );

            if (existingPayment) {
                let existingSum = +existingPayment.sum;
                let incomingSum = +v.sum;

                existingSum += incomingSum ? incomingSum : 0;

                existingPayment.sum = "" + existingSum;
            } else {
                newPayments.push({
                    currency: v.currency,
                    sum: v.sum ? v.sum : 0
                });
            }
        });

        value["0"].payments = newPayments;
    });

    return history;
}

使用它傳遞您的對象,說您將其paymentHistory sumByCurrency函數的sumByCurrency像這樣:

sumByCurrency(paymentHistory);

請注意:如果value["0"].payments不可用,您可能希望進行一些后備/確保它不會中斷。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM