[英]How can I use all function arguments inside javascript Object.assign method
我正在使用nodejs
& express 制作一個服務器,用戶可以在其中請求一些數據和服務器發送響應。 但是,數據是數組,我想向用戶發送一個 json 響應。 因此,我使用了數組的forEach()
方法並使用Object.assign()
,以便我可以獲取對象。 但問題是我不能使用forEach()
方法的 'index' 參數,而在回調函數中正確使用了 'value' 參數。 當我只使用 'index' 參數時,我的代碼運行正常,但我想同時使用這兩個參數。
route.get('/getGPX/:number', passport.authenticate('jwt', { session: false }), (req, res) => {
gpx.find({ username: req.user.username }, (err, result) => {
if (err) console.log(err);
if (result) {
if (result.length === 0) {
res.end();
console.log('ended')
}
else {
var jsonRes = {};
result.forEach((value, index) => {
我可以使用參數中的“值”但不能使用“索引”
jsonRes = Object.assign({ index: value.data }, jsonRes);
})
res.json({data: jsonRes});
}
}
})
我什至嘗試使用global var
,但即使它不起作用,我怎樣才能同時使用 index 和 value 參數
你想要的 JSON 結構是什么?
如果你想要一個像這樣的json:
{
0: "my first value",
1: "second"
}
您只是錯過了索引周圍的[]
,在這里您將“索引”作為鍵而不是索引的值。 所以你在每次迭代中覆蓋索引鍵。
這是使用 index 的值作為 json 中的鍵的代碼。
jsonRes = Object.assign({[index]: value.data}, jsonRes)
有關更多示例的工作示例,請參見此處: https : //repl.it/@Benoit_Vasseur/nodejs-playground
Object.assign
改變了最左邊的參數。 它不會產生新對象。 由於每次 jsonRes 將成為最后一個結果時,您都會傳遞一個文字對象。
將 jsonRes 放在左側 - Object.assign(jsonRes, {index: value.data})
您可能想要使用簡單的reduce
而不是forEach
和Object.assign
:
} else {
var jsonRes = result.reduce((r, v, i) => {r[i] = v.data; return r}, {});
res.json({data: jsonRes});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.