简体   繁体   中英

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.

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

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

在JavaScript 1.6及更高版本中:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM