1

This might be a quite easy question, but I haven't encountered an elegant solution.

How do you get all objects from an array by a single field. For example;


var users = [{name:'John', age: 20}, 
{name:'Sarah', age: 21}, 
{name:'George', age:34}];
var names = magicFunction(users, 'name');
// names = ['John', 'Sarah', 'George']; 
// Another challenge is not to get field name (in this case 'name') with the value

I wonder if you could do it with functions like filter or map, without writing a long function?

3 Answers 3

2

Yes, it's pretty straight forward:

var prop = 'name';
var names = users.map(function(x) { return x[prop]; });

Or if you want to write this into a function:

function getProp(arr, prop)
{
    return arr.map(function(x) { return x[prop]; });
}

var names = getProp(users, 'name');

Update In ES6 syntax:

const getProp = (arr, prop) => Array.prototype.map.call(arr, x => x[prop]);
const names = getProp(users, 'name');
Sign up to request clarification or add additional context in comments.

Comments

1

Underscore.js (which you can install as a node package) has a function called _.pluck which does exactly this. If you _ = require("underscore") you can actually replace magicFunction with _.pluck.

Comments

0

@p.s.w.g is probably the solution you're looking for, but I'd like to show another one: using core.operators.

var names = users.map(opts.get('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.