我正在尝试使用现有数组中的有限值创建新数组。在下面的示例中,LargeArray
包含许多属性 - 年份,书籍,gdp和控件。让我们说我想创建一个只包含year和gdp的新数组。
var LargeArray = [
{year:1234, books:1200, gdp:1200, control:1200},
{year:1235, books:1201, gdp:1200, control:1200},
{year:1236, books:1202, gdp:1200, control:1200}
];
我想要的新数组看起来像这样:
var NewArray = [
{year:1234, gdp:1200},
{year:1235, gdp:1200},
{year:1236, gdp:1200}
];
答案 0 :(得分:4)
使用$.map()
var LargeArray = [{year:1234, books:1200, gdp:1200, control:1200}, {year:1235, books:1201, gdp:1200, control:1200}, {year:1236, books:1202, gdp:1200, control:1200}, {year:1237, books:1203, gdp:1200, control:1200}, {year:1238, books:1204, gdp:1200, control:1200}];
var NewArray = $.map(LargeArray, function (value) {
return {
year: value.year,
gdp: value.gdp
}
})
演示:Fiddle
答案 1 :(得分:0)
var newArray = largeArray.map(function(obj) {
return { year: obj.year, gdp: obj.gdp };
});
注意:Array.prototype.map
是最近添加的内容。使用MDN中的填充程序来支持旧浏览器。