Javascript array of object to array of string, simpler way?
I am so used to the syntactic sugar of C# (and not as used to javascript as I want to) tha开发者_开发问答t I find this very verbose.
Is there any better way to do this?
var justColumnNames = new Array();
for( i= 0; i< columnsInfo.length; i++)
{
justColumnNames[i] = columnsInfo[i].Name;
}
(BTW I have the Extjs available in the page, and I cant really use any other library) Thanks
Ext.each( columnsInfo, function(elem){
justColumnNames.push(elem.name);
});
What you're looking for is a map()
function, which takes the values in an array, applies a function to each value and returns an array containing the mapped values. I'm not familiar enough with ExtJS to know if it includes a map function by default, but this question links to some plugins you can use.
Once you have a map function available, you can do something like this:
justColumnNames = columnsInfo.map(function(elem) { elem.Name });
You can easily add syntactic sugar in javascript. One common one is to implement a foreach/map/filter method for arrays. Most libraries do this. My implementation:
// List object, inherits from Array
function List (array) {
// Allow List constructor to convert
// Array object into List object:
if (array !== undefined) {
this.push.apply(this,array)
}
// each() method. A cross between map and filter:
this.each = function (callback) {
var ret = new List();
for (i=0,l=this.length;i<l;i++) {
var r = callback(this[i],i);
if (r !== undefined) {
ret.push(r);
}
}
return ret;
}
}
List.prototype = new Array();
// Direct translation of your code:
var justColumnNames = new List();
justColumnNames.each(function(n,i){
n = columnsInfo[i].Name;
});
// Or the more brief:
var justColumnNames = new List(columnsInfo).each(function(n){return n.Name});
Some people modify the Array constructor directly by doing:
Array.prototype.each = function (callback) {
// see implementation above ...
}
But I generally don't like modifying native objects.
精彩评论