Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash get nested object property with pluck

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?

like image 968
Nikola Avatar asked Oct 22 '15 11:10

Nikola


1 Answers

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 ]
like image 94
thefourtheye Avatar answered Oct 02 '22 07:10

thefourtheye