-3

I have this array of objects:

this.clients=[{firstName:"Tywin", lastName:"Lannister", age:46, id:2},
              {firstName:"Arya", lastName:"Starck", age:46, id:-1},
              {firstName:"John", lastName:"Snow", age:46, id:12},
              {firstName:"Robb", lastName:"Starck", age:46, id:24}];

And this variable:

var idArr;

I need to iterate threw all objects in array and get all id's and create array from them.Like that:

idArr = [2,-1,12,24]

How can I implement it using lodash?

Michael
  • 13,950
  • 57
  • 145
  • 288

1 Answers1

5

Use Array#map method

this.clients=[{firstName:"Tywin", lastName:"Lannister", age:46, id:2},
              {firstName:"Arya", lastName:"Starck", age:46, id:-1},
              {firstName:"John", lastName:"Snow", age:46, id:12},
              {firstName:"Robb", lastName:"Starck", age:46, id:24}];

var idArr = this.clients.map(function(v){ return v.id; })

console.log(idArr);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • Any idea why I get syntex error on this "=>" – Michael Jun 11 '16 at 16:53
  • @Michael because arrow functions are ES6 and only supported in strict mode (`'use strict'`) in modern browsers. Check the duplicate question in my comment to your answer for a version with a regular callback function. – t.niese Jun 11 '16 at 16:55
  • @Michael : it's ES6 arrow function, only works in latest browser.... so answer updated with normal function – Pranav C Balan Jun 11 '16 at 16:55