I'm hoping to take advantage of underscore to avoid writing for
loops throughout my code base. I'm using map
in place of a for
loop like so:
body.tags = _.map(body.tags, function(tag) {
return {
id: tag.id,
userId: tag.userId,
createDate: tag.createDate,
tag: tag.tag.toLowerCase(),
};
});
My question is, is there a way to do this without specifying the properties that won't be changing (everything but tag
)? It seems like overkill to specify fields like id: tag.id
.
You could try the following code to change a single property in a collection using underscore.
_.map(body.tags, function(tag) {
tag.tag = tag.tag.toLowerCase();
return tag;
});
There is one benefit in using lodash's map method (similar to underscore library) over native forEach and its performance. Based on why lodash is faster than native forEach post, maybe it's justifiable to use lodash in favour of both underscore and native forEach to loop. However I would agree with the user who commented below "Choose the approach that is most writable, readable, and maintainable".
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