我試圖使用forEach循環和數組[鍵] .transactions添加對象添加對象(事務)數組到數組(票據)。 我也嘗試使用推,但沒有工作。使用forEach()添加一個數組到一個對象()
一些幫助將是可愛的。
var bills = [{
"_id": "5499aece1d7be6c6a3000001",
"billName": "Insurance",
"startDate": "2014-12-15T00:00:00.000Z",
"amount": 2400,
"type": 4,
"timestamp": "2014-12-23T18:05:02.987Z",
"__v": 0
}, {
"_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
}];
var transactions = [{
"_id": "549ea8c957b654ef64000003",
"billId": "5499aece1d7be6c6a3000001",
"paymentDate": "2014-12-27T12:40:41.311Z",
"amount": 2400,
"timestamp": "2014-12-27T12:40:41.311Z",
"__v": 0
}, {
"_id": "549ea8e632ed3f6265000001",
"billId": "549bf0597886c3763e000001",
"paymentDate": "2014-12-27T12:41:10.582Z",
"amount": 16500,
"timestamp": "2014-12-27T12:41:10.582Z",
"__v": 0
}, {
"_id": "549ea93452ebbd8366000001",
"billId": "549bf0597886c3763e000001",
"paymentDate": "2014-12-27T12:42:28.744Z",
"amount": 16500,
"timestamp": "2014-12-27T12:42:28.745Z",
"__v": 0
}];
和
var test = [];
bills.forEach(function (bill, key) {
test.push(bill);
transactions.forEach(function (transaction) {
if (transaction.billId == bill._id) test[key].transactions = transaction;
});
});
console.log(test);
最終結果應當是測試對象將攜帶各紙幣的對象內部的紙幣加上交易作爲對象陣列。
編輯
的問題是,這種代碼在的jsfiddle但是當我應用到陣列從貓鼬發現()正在添加不起作用。 下面是完整的代碼:
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];
var test = [];
// var test.transactions = [];
bills.forEach(function(bill, key) {
bill.transactions = transactions.filter(function (transaction) {
return transaction.billId === bill._id;
});
console.log(bill.transactions);
test.push(bill);
});
console.log(transactions);
res.send(test);
});
});
此,返回此:
[{"_id":"5499aece1d7be6c6a3000001","billName":"Jeep Insurance","startDate":"2014-12-15T00:00:00.000Z","amount":2400,"type":4,"timestamp":"2014-12-23T18:05:02.987Z","__v":0},{"_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},{"_id":"54a014bfac01ca3526000001","billName":"Test","startDate":"2014-10-28T00:00:00.000Z","endDate":"2017-12-19T23:00:00.000Z","amount":1000,"type":4,"timestamp":"2014-12-28T14:33:35.233Z","__v":0}]
我是歡迎您!
@Deisy Laymi lean()將MongooseDocument轉換爲純JavaScript對象... http://goo.gl/kxicLp –