0

In Objective-C, if I have an array of objects and each object has a key of id like so:

NSArray *array = @[@{@"id":@(1), @"name":@"Bob"}, @{@"id":@(2), @"name":@"Frank"}, @{@"id":@(3), @"name":@"Joe"}];

I could call [array valueForKey:@"id"] and get an array of just the ids.

How can I do this in Node/Javascript? If I set up my javascript array like this:

var array = [{"id":1, "name":"Bob"}, {"id":2, "name":"Frank"}, {"id":3, "name":"Joe"}];

I would like to be able to do this:

var idsArray = array.valueForKey("id");

How should I go about achieving this?

Thanks!

Jason Silberman
  • 2,471
  • 6
  • 29
  • 47
  • http://stackoverflow.com/questions/7364150/find-object-by-id-in-array-of-javascript-objects – Matt Way May 11 '14 at 16:00
  • @MattWay, that link describes finding an object by ID, not getting a list of all IDs. – Buck Doyle May 11 '14 at 16:03
  • 1
    @BuckDoyle True. I didn't remove it however, because it is quite similar, and contains many good answers that would be worth reading. – Matt Way May 12 '14 at 04:02

1 Answers1

3

You can use map for that:

array.map(function (obj) { return obj.id; });

or if you have underscore in your project you can use pluck:

_.pluck(array, 'id');
vkurchatkin
  • 13,364
  • 2
  • 47
  • 55