LoDash: Get an array of values from an array of object properties

感情迁移 提交于 2019-12-20 08:04:04

问题


I'm sure it's somewhere inside the LoDash docs, but I can't seem to find the right combination.

var users = [{
      id: 12,
      name: Adam
   },{
      id: 14,
      name: Bob
   },{
      id: 16,
      name: Charlie
   },{
      id: 18,
      name: David
   }
]

// how do I get [12, 14, 16, 18]
var userIds = _.map(users, _.pick('id'));

回答1:


Since version v4.x you should use _.map:

_.map(users, 'id'); // [12, 14, 16, 18]

this way it is corresponds to native Array.prototype.map method where you would write (ES2015 syntax):

users.map(user => user.id); // [12, 14, 16, 18]

Before v4.x you could use _.pluck the same way:

_.pluck(users, 'id'); // [12, 14, 16, 18]



回答2:


With pure JS:

var userIds = users.map( function(obj) { return obj.id; } );



回答3:


In the new lodash release v4.0.0 _.pluck has removed in favor of _.map

Then you can use this:

_.map(users, 'id'); // [12, 14, 16, 18]

You can see in Github Changelog




回答4:


And if you need to extract several properties from each object, then

let newArr = _.map(arr, o => _.pick(o, ['name', 'surname', 'rate']));



回答5:


If you are using native javascript then you can use this code -

let ids = users.map(function(obj, index) {

    return obj.id;
})

console.log(ids); //[12, 14, 16, 18]



回答6:


This will give you what you want in a pop-up.

for(var i = 0; i < users.Count; i++){
   alert(users[i].id);  
}


来源:https://stackoverflow.com/questions/28354725/lodash-get-an-array-of-values-from-an-array-of-object-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!