[javascript] LoDash: Get an array of values from an array of object properties

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'));

This question is related to javascript lodash

The answer is


_x000D_
_x000D_
const users = [{
      id: 12,
      name: 'Adam'
   },{
      id: 14,
      name: 'Bob'
   },{
      id: 16,
      name: 'Charlie'
   },{
      id: 18,
      name: 'David'
   }
]
const userIds = _.values(users);
console.log(userIds); //[12, 14, 16, 18]
_x000D_
_x000D_
_x000D_


Simple and even faster way to get it via ES6

let newArray = users.flatMap(i => i.ID) // -> [ 12, 13, 14, 15 ]

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]

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

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

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


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

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

With pure JS:

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