Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
43
rated 0 times [  49] [ 6]  / answers: 1 / hits: 82681  / 10 Years ago, thu, june 26, 2014, 12:00:00

If I have an object such that



var object = function(key,text)
{
this.key = key;
this.text = text;
}


And create an array of these objects



var objArray = [];
objArray[0] = new object('key1','blank');
objArray[1] = new object('key2','exampletext');
objArray[2] = new object('key3','moretext');


is there a way that I can retrieve only one of the properties of all of the objects in the array? For example:



var keyArray = objArray[key]; 


The above example doesn't return set keyArray to anything, but I was hoping it would be set to something like this:



keyArray = [
'key1',
'key2',
'key3']


Does anyone know of a way to do this without iterating through the objArray and manually copying each key property to the key array?


More From » arrays

 Answers
50

This is easily done with the Array.prototype.map() function:



var keyArray = objArray.map(function(item) { return item[key]; });


If you are going to do this often, you could write a function that abstracts away the map:



function pluck(array, key) {
return array.map(function(item) { return item[key]; });
}


In fact, the Underscore library has a built-in function called pluck that does exactly that.


[#70411] Wednesday, June 25, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hayleevalenciac

Total Points: 164
Total Questions: 89
Total Answers: 106

Location: Burkina Faso
Member since Thu, Dec 15, 2022
1 Year ago
;