最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Use underscore to change one property of objects in an array - Stack Overflow

programmeradmin3浏览0评论

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.

Share Improve this question edited Aug 25, 2015 at 3:35 user663031 asked Aug 24, 2015 at 19:44 MattDionisMattDionis 3,61610 gold badges54 silver badges109 bronze badges 3
  • Is body.tags an array? – Amit Commented Aug 24, 2015 at 19:47
  • @Amit, yes body.tags is an array of objects, each with the structure shown within the return block. – MattDionis Commented Aug 24, 2015 at 19:48
  • If you want to continue to use your _.map approach, then you could say return _.extend(tag, { tag: tag.tag.toLowerCase() });. However, the answer using forEach is better. – user663031 Commented Aug 25, 2015 at 3:36
Add a comment  | 

2 Answers 2

Reset to default 10

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

发布评论

评论列表(0)

  1. 暂无评论