开发者

Creating an array of properties from an array of objects with JSON

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)


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.


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);});


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; });


In JavaScript 1.6 and later:

group.map(function(p) { return p.Name; });

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜