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

假装没事ソ 提交于 2019-12-02 14:13:06

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]

With pure JS:

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

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

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

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

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]
user1789573

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

for(var i = 0; i < users.Count; i++){
   alert(users[i].id);  
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!