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
.
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
.
2 Answers
Reset to default 10You don't even need underscore for this:
body.tags.forEach(function(t) { t.tag = t.tag.toLowerCase();});
map
(whether native, underscore or others) is used to transform whole values, it's not a typical use case to do what you tried to do with it. Also, using a simple for
might perform better since you don't need function calls here, but that depends on runtime optimizations.
By the way, if you replace the mapping function with the function from this answer and not set the return value back to body.tags
, you'll also get your desired result.
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".
body.tags
is an array of objects, each with the structure shown within thereturn
block. – MattDionis Commented Aug 24, 2015 at 19:48_.map
approach, then you could sayreturn _.extend(tag, { tag: tag.tag.toLowerCase() });
. However, the answer usingforEach
is better. – user663031 Commented Aug 25, 2015 at 3:36