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

JavascriptLodash

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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]

Solution 2 - Javascript

With pure JS:

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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

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

Solution 5 - Javascript

Simple and even faster way to get it via ES6

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

Solution 6 - Javascript

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]

Solution 7 - Javascript

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]

Solution 8 - Javascript

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYarGnawhView Question on Stackoverflow
Solution 1 - JavascriptdfsqView Answer on Stackoverflow
Solution 2 - Javascriptc-smileView Answer on Stackoverflow
Solution 3 - JavascriptiarroyoView Answer on Stackoverflow
Solution 4 - JavascriptAndreyView Answer on Stackoverflow
Solution 5 - JavascriptGYTOView Answer on Stackoverflow
Solution 6 - JavascriptWajid Raza SaeediView Answer on Stackoverflow
Solution 7 - JavascriptPankaj BishtView Answer on Stackoverflow
Solution 8 - Javascriptuser1789573View Answer on Stackoverflow