0

I want to transform an object like this:

[
  { name: 'john', surname: 'doe' },
  { name: 'jane', surname: 'dee' },
]

Into an array, like this. By choosing an arbitrary key (e.g: 'name')

[ 'john', 'jane' ]

What is the fastest way to achieve this? Thanks in advance.

1
  • 3
    Have you tried the slowest way? Commented Jan 29, 2014 at 8:05

3 Answers 3

3

Try use map function like this

[
    { name: 'john', surname: 'doe' },
    { name: 'jane', surname: 'dee' },
].map(function(a){return a.name;})    
Sign up to request clarification or add additional context in comments.

2 Comments

Note that Array#map is an ES5 thing, but that's fine, this is NodeJS. (In client-side stuff, older browsers would need a shim.)
@Peter: No worries. :-) We should clean up these comments. I've done mine. This comment will auto-destruct in 10...9...8...
1

If you don't need retro compatibility (and I think you're not going to need it, since you're on NodeJS), you can simply use:

var obj = [
    { name: 'john', surname: 'doe' },
    { name: 'jane', surname: 'dee' },
],
    names = obj.map(function(item) {return item.name;});

Or, the "slowest" way:

var names = []; //obj defined before
for(var i = 0; i < obj.length; i++) 
    names.push(obj[i].name);

2 Comments

Ironically, it turns out Array.prototype.map is generally slower than a simple for loop. The native map function just does more error checking internally and has the overhead of an additional function invocation for every iteration: jsperf.com/array-map-test
@Peter, I know, in fact I put the quotes because it's not slowest at any point, it's just "slower" to write :P
0

If you are using UnderscoreJS, you can simply write:

names = _.pluck(obj, 'name');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.