仅使用包含特定值的元素从现有数组创建新数组

Create new array from existing one only with elements that contain specific value

我从现有数组创建一个新数组(包含 100.000 个对象的大数组)。在新数组中,我只想要 "city" 的值为例如纽约市的元素。

    var newData = [];

    for (var i = 0; i < data.length; i++) {

        if(data[i].city === "New York City") {

            newData[i] = {"city": data[i].city, "longitude": 
            data[i].longitude, "latitude": data[i].latitude, "state": 
            data[i].state};

        }
     }

我一定是做错了什么,因为新数组中的很多元素是 null

新数组看起来像这样:

[null,null,null,null,null, {"city":"New York", "logitude": 
-73.935242, "latitude": 40.730610, "state": "NY"},
null,null,null,null,null,null,"city":"New York", "logitude": 
-73.935242, "latitude": 40.730610, "state": "NY"}]

我做错了什么?我怎样才能实现我的目标?

提前谢谢大家!

元素不会 null,它们会 缺失 (当您尝试访问它们时显示为 undefined)。原因是你每次都在增加 i,即使你跳过了一个条目。

要修复它,请改用 push

var newData = [];

for (var i = 0; i < data.length; i++) {

    if (data[i].city === "New York City") {
        newData.push({
            "city": data[i].city,
            "longitude": data[i].longitude,
            "latitude": data[i].latitude,
            "state": data[i].state
        });
    }
}

如果你想让两个数组共享个对象,你可以使用filter代替:

var newData = data.filter(function(entry) {
    return entry.city === "New York City";
});

但是如果您希望新数组具有与原始数组不同的新对象,您的for循环就可以了。

可以使用Array.prototype.filter方法:

newData.filter(function (el) {
  return el.city === "New York City";
});

或者如果您需要其他过滤器参数:

newData.filter(function (el) {
  return el.city === "New York City" && el.state === "NY" ;
});

此方法是新 ECMAScript 5th Edition standard 的一部分。

来自文档:

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.