How to get nested object property with pluck in Lodash

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts, I will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

This Lodash question was actually asked by myself:

I have an array of objects like this:

var characters = [
    { 'name': 'barney',  'age': 36, 'salary':{'amount': 10} },
    { 'name': 'fred',    'age': 40, 'salary':{'amount': 20} },
    { 'name': 'pebbles', 'age': 1,  'salary':{'amount': 30} }
];

I want to get the salary amounts into an array. I managed to do it by chaining two pluck functions, like this:

var salaries = _(characters)
  .pluck('salary')
  .pluck('amount')
  .value();

console.log(salaries); //[10, 20, 30]

Is there a way to do this by using only one pluck? Is there a better way with some other function in lodash?

The answer, from user thefourtheye, was:

You can just give the path to be used as a string, like this

console.log(_(characters).pluck('salary.amount').value())
// [ 10, 20, 30 ]

Or use it directly

console.log(_.pluck(characters, 'salary.amount'));
// [ 10, 20, 30 ]

https://twitter.com/HitmanHR/status/670237244695977984

Written by Nikola Brežnjak