从现有数组属性创建新的数组

4

我正在尝试从现有的数组中限制值来创建一个新的数组。在下面的示例中,LargeArray 包含许多属性 - 年份、书籍、GDP 和控制等。假设我想创建一个只包括年份和 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}
];

我想使用Jquery来创建新的数组,我不确定map函数是否有帮助。如果使用纯JavaScript会更好的话也行。 - Rohan Sandeep
2个回答

5

使用 $.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


我刚查了一下$.map,它提到要通过$.makeArray运行数组——这在这里是否相关? - Sterling Archer
@RUJordan 不是的,因为 OP 有一个实际的数组。 - Arun P Johny

3
使用Array.prototype.map
var newArray = largeArray.map(function(obj) {
  return { year: obj.year, gdp: obj.gdp };
});

注意:`Array.prototype.map` 是最近才添加的。使用 MDN 的 shim 支持旧浏览器。 jsFiddle 演示

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接