我想添加一些額外的值到數組中的每個項目。所以我有一個包含對象的數組,它們有:x,y和z字段。然後我想根據http.get調用的響應將其他項添加到數組中的每個對象。ForEach不更新主陣列
主陣列是:帖子
下面見代碼:
router.get('/api/posts', function(req, res){
postModel.find({})
.limit(10)
.exec(function(err, posts) {
var options = {
host: 'localhost',
port: 3000,
path: '/user?id=12345678',
method: 'GET'
};
if(posts){
posts.forEach(function(post) {
var req = http.get(options, function(res) {
var bodyChunks = [];
res.on('data', function(chunk) {
bodyChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(bodyChunks);
var parsedBody = JSON.parse(body);
post.fullname = parsedBody.user.fullname;
post.profilePic = parsedBody.user.profilePic;
});
});
});
res.json({
posts : posts
});
} else {
res.send('Post does not exist');
}
});
});
在post.profilePic = parsedBody.user.profilePic的時間 - profilePic變量是有但是當我通過res.json得到來自節點的響應時,附加值不是。
我在這裏錯過了什麼?我始終在Angular前端使用這種方法,而沒有任何問題。
謝謝
嘗試一件事:將'post'分配給某個變量'var temp = post'。然後將'fullname'和'profilePic'添加到該變量'temp.fullname = parsedBody.user.fullname;'和'post.profilePic = parsedBody.user.profilePic'。現在返回'temp'而不是'posts'。 –
感謝您的評論。這種方法可行,但肯定有一個更原始的方式是正確的?我將不得不推入數組,其中大部分數據已經存在,這會導致內存的巨大開銷(真實數據很大)。 –