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

javascript - Retrieve only one field from objectarray using underscore.js - Stack Overflow

programmeradmin3浏览0评论

In ruby I'm able to do the following:

myObject.map(&:name)

And I get an array composed by all the name field for all values inside myObject (array or object).

What's the underscore.js or lodash.js equivalent? I prefer in only one line if possible :)

Example: (in js)

_.map([{name: 'x'}, {name: 'y'}], function(obj){
    //dosomething
})

In ruby I'm able to do the following:

myObject.map(&:name)

And I get an array composed by all the name field for all values inside myObject (array or object).

What's the underscore.js or lodash.js equivalent? I prefer in only one line if possible :)

Example: (in js)

_.map([{name: 'x'}, {name: 'y'}], function(obj){
    //dosomething
})
Share Improve this question asked Feb 25, 2014 at 21:25 VadorequestVadorequest 18k27 gold badges129 silver badges231 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 12
_.pluck([{name: 'x'}, {name: 'y'}],"name"); 

this will give you: ["x","y"];

see http://underscorejs.org/#pluck

For lodash users,

_.map([{'name': 'x'}, {'name': 'y'}], 'name');

// ['x', 'y'] 

Using pure Javascript simply use map

let data = [{name: 'x'}, {name: 'y'}];
data.map( (item) => item.name );

Will return you ["x", "y"].

发布评论

评论列表(0)

  1. 暂无评论