Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use underscore to change one property of objects in an array

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.

like image 890
MattDionis Avatar asked Aug 24 '15 19:08

MattDionis


1 Answers

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".

like image 183
invalidred Avatar answered Oct 14 '22 02:10

invalidred