Returning only certain properties from an array of objects in Javascript [duplicate]
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.
var object = function(key,text) { this.key = key; this.text = text;}var objArray = [];objArray[0] = new object('key1','blank');objArray[1] = new object('key2','exampletext');objArray[2] = new object('key3','moretext');var keys = objArray.map(function(o,i) { return o.key;});console.log(keys); // ["key1", "key2", "key3"]
JS Bin Example
Note that older browsers may not support map but you can easily do this with a for
loop:
var keys = [];for (var i = 0; i < objArray.length; i++) { keys.push(objArray[i].key);}
JS Bin Example
You would want to do something like this:
objArray.map(function (obj) { return obj.key; });
Here is a JSFiddle to demo: http://jsfiddle.net/Q7Cb3/
If you need older browser support, you can use your own method:
JSFiddle demo: http://jsfiddle.net/Q7Cb3/1/
function map (arr, func) { var i = arr.length; arr = arr.slice(); while (i--) arr[i] = func(arr[i]); return arr;}