简体   繁体   English

使用JSON从对象数组创建属性数组

[英]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) 在c#中,与: 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 JSFiddle示例

You could also try a seperate library like LINQ to JavaScript which looks quite useful. 您也可以尝试一个单独的库,如LINQ to JavaScript ,看起来非常有用。

You could use .map , but it's not available in older browsers. 您可以使用.map ,但在旧版浏览器中不可用。

// 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: 我将提供明显的一个直接javascript,适用于所有浏览器:

var names = [];
for (var i = 0; i < group.length; i++) {
    names.push(group[i].Name);
}

Or with jQuery (using it's .map utility method): 或者使用jQuery(使用它的.map实用程序方法):

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: 或者,如果您安装.map填充程序以确保.map Array方法在所有浏览器中都可用:

var names = group.map(function(item) {return(item.Name);});

在JavaScript 1.6及更高版本中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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