admin管理员组

文章数量:1290237

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?

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?

Share Improve this question edited Oct 22, 2015 at 11:55 thefourtheye 240k53 gold badges465 silver badges500 bronze badges asked Oct 22, 2015 at 11:21 NikolaNikola 15k21 gold badges106 silver badges170 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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 ]

本文标签: javascriptLodash get nested object property with pluckStack Overflow