3
function Person(name, favouriteColour) {
   this.Name = name;
   this.FavouriteColour = favouriteColour;
}

var group = [];

group.push(new Person("Bob", "Green"));
group.push(new Person("Jane", "Red"));
group.push(new Person("Jack", "Blue"));

What could I do to get an array of Names from group?

group.??? -> ["Bob", "Jane", "Jack"]

In c#, the same as: group.ConvertAll<string>(m => m.Name)

1
  • Are you using jQuery or anything else? Commented Oct 3, 2011 at 15:26

4 Answers 4

3

I think you'll just have to loop over the array and get the names that way.

function getKeysArray(key, objArray) {
    var result = [], l = objArray.length;
    for (var i = 0; i < l; i++) {
        result.push(objArray[i][key]);
    }
    return result;
}

alert(getKeysArray("Name", group));

JSFiddle Example

You could also try a seperate library like LINQ to JavaScript which looks quite useful.

Sign up to request clarification or add additional context in comments.

2 Comments

What is the file size overhead for Linq to Javascript?
I have no idea, I've never used it but seen it recommended on here before. Just downloaded it and it's 6.9kb.
2

I'll offer the obvious one with straight javascript that works in all browsers:

var names = [];
for (var i = 0; i < group.length; i++) {
    names.push(group[i].Name);
}

Or with jQuery (using it's .map utility method):

var names = $.map(group, function(item) {return(item.Name);});

Or, if you install a .map shim to make sure the .map Array method is available in all browsers:

var names = group.map(function(item) {return(item.Name);});

1 Comment

Thanks, you weren't the first one with these answers, but you provided the most robust selection. I went with the jQuery's map method. Very nice!
2

You could use .map, but it's not available in older browsers.

// names is group's Name properties
var names = group.map(function(value) { return value.Name; });

Comments

1

In JavaScript 1.6 and later:

group.map(function(p) { return p.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.