_.map() 在播放真实数据时不起作用

_.map() not working when playing with real data

本文关键字:真实 数据 不起作用 播放 map      更新时间:2023-09-26

我正在查询两个集合以从账单和交易中获取数据。

在我得到两者之后,我为每个billId循环事务数组。

一旦事务数组中的billId与账单数组中的_id匹配,我就会将事务存储在账单数组下。

因此,与其拥有:

bill_array = [{
    "_id": "549bf0597886c3763e000001",
    "billName": "Leasing",
    "startDate": "2014-12-25T00:00:00.000Z",
    "endDate": "2017-10-14T22:00:00.000Z",
    "amount": 16500,
    "type": 4,
    "timestamp": "2014-12-25T11:09:13.957Z",
    "__v": 0
}]

我可以有:

bill_array = [{"_id": "549bf0597886c3763e000001",
    "billName": "Leasing",
    "startDate": "2014-12-25T00:00:00.000Z",
    "endDate": "2017-10-14T22:00:00.000Z",
    "amount": 16500,
    "type": 4,
    "transactions": {[all transactions]}
    "timestamp": "2014-12-25T11:09:13.957Z",
    "__v": 0}]

下面的代码在我的 JSfiddle 测试中工作,但是,当我尝试使用真实数据(来自数据库)时,我无法让映射将新对象插入到 bills 数组中。以下是工作示例:http://jsfiddle.net/dennislaymi/usanwkcL/

这是我机器上的(不起作用的)代码:

app.get('/getbills', function(req, res) {
    //get all bills
    allBills = Bills.find().exec();
    //get all transactions
    allTransactions = Transactions.find().exec();
    //aggregate bills and transactions in a promise
    promise.all([allBills, allTransactions]).then(function(results) {
        var bills = results[0];
        var transactions = results[1];
        _.map(bills, function(bValue) {
            bValue.transactions = [];
            _.each(transactions, function(tValue) {
                if (tValue.billId == bValue._id) {
                    bValue.transactions.push(tValue);
                }
            });
            console.log("transactons: " + bValue.transactions);
            return bValue.transactions;
        });
        console.log(bills);
        res.send(bills);
    });
});

_.map是一个不可变的操作,这意味着它不会更改初始对象。

如果你想用映射数据覆盖它,你应该写这样的东西:

bills = _.map(bills, function (bValue) {
  bValue.transactions = [];
  _.each(transactions, function (tValue) {
    if (tValue.billId == bValue._id) {
      bValue.transactions.push(tValue);
    }
  });
  return bValue;
});

我还建议在您的情况下使用 _.filter 而不是 _.each 这样的东西:

bills = _.map(bills, function (bValue) {
  bValue.transactions = _.filter(transactions, function (tValue) {
    return (tValue.billId == bValue._id);
  });
  return bValue;
});