lets say each post in my posts array has two properties name and number. so its something like
var posts = [{name:"hey", number: 1}, {name:"foo", number:"2"}]
Javascript allows me to change these properties in foreach loop like this:
posts.forEach(function(post){
post.name = "bar"
});
and my array becomes:
var posts = [{name:"bar", number: 1}, {name:"bar", number:"2"}]
but it doesnt allow me add a new property like:
posts.forEach(function(post){
post.adress = "bar"
});
my object stays the same. Is there a way to add properties in a foreach loop in javascipt
edit:
this is happening using mongoose inside a callback..
Post.pagination(options, function(err, posts) {
if (err) console.log(err)
posts.forEach(function(post){
post.votetype = 1;
});
console.log(posts);
res.send({ posts : posts })
})
after this votetype property is not added
From the official MDN docs: There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.
The forEach method does not return a new array like other iterators such as filter , map and sort . Instead, the method returns undefined itself.
JavaScript's Array#forEach() function lets you iterate over an array, but not over an object. But you can iterate over a JavaScript object using forEach() if you transform the object into an array first, using Object. keys() , Object. values() , or Object.
The forEach() method executes a provided function once for each array element.
The problem is that data returned from Mongoose is immutable. The code below is untested but should give you a hint on how to make the data mutable and modify it.
The key point is calling toObject()
on the Mongoose document object you wish to modify.
Post.pagination(options, function(err, posts) {
if (err) console.log(err);
var resultPosts = posts.map(function(post) {
var tmpPost = post.toObject();
// Add properties...
tmpPost.votetype = 1;
return tmpPost;
});
console.log(resultPosts);
res.send({ posts : resultPosts });
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With