Question

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!

Was it helpful?

Solution

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');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top