Use underscore to change one property of objects in an array

I hope to use an underscore to avoid writing for loops throughout the code base. I use map instead of a for loop like this:

 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 properties that will not change (everything except tag )? id: tag.id seems to indicate fields of type id: tag.id

+6
source share
2 answers

You do not even need to emphasize:

 body.tags.forEach(function(t) { t.tag = t.tag.toLowerCase();}); 

map (whether native, underscore or others) is used to convert integer values, this is not a typical use case to do what you tried to do with it. Also, using a simple for may work better, since you don't need function calls here, but it depends on optimizing the runtime.

By the way, if you replace the matching function with the function from this answer and don’t set the return value to body.tags , you will also get the desired result.

+8
source

You can try the following code to change one property in a collection using underscores.

 _.map(body.tags, function(tag) { tag.tag = tag.tag.toLowerCase(); return tag; }); 

There is one advantage to using the lodash map method (similar to the underline library) over native forEach and its performance. Based on why lodash is faster than native forEach , perhaps this is justified for using lodash in favor of both underscore and native forEach for the loop. However, I would agree with the user who commented below, "Choose the approach that is most accessible for writing, reading, and accompanying."

+5
source

All Articles