$scope.locations = [
{ name : "One"},
{ name : "Two"},
{ name : "Three"},
{ name : "India"},
{ name : "Japan"},
{ name : "China"}
];
$scope.tempLocations = [
{ name : "One"},
{ name : "Two"},
{ name : "global"},
];我有两个数组。如果location不包含tempLocations中的一些名称,我想从tempLocation中删除它们。在本例中,我希望删除位置全局
我试过以下几种方法,但不起作用。
for(var i=0;i<$scope.tempLocations.length;i++){
var index = $scope.tempLocations.indexOf($scope.locations[i]);
if(index == -1){
console.log($scope.tempLocations[i]);
$scope.tempLocations.splice(i,1);
}
}发布于 2014-09-17 14:33:09
我想你是在找这个
$scope = {}
$scope.locations = [
{ name : "One"},
{ name : "Two"},
{ name : "Three"},
{ name : "India"},
{ name : "Japan"},
{ name : "China"}
];
$scope.tempLocations = [
{ name : "One"},
{ name : "Two"},
{ name : "global"},
];
$scope.tempLocations = $scope.tempLocations.filter(function(x) {
return $scope.locations.some(function(y) {
return x.name == y.name
})
})
document.getElementById("output").innerHTML = JSON.stringify($scope.tempLocations, 0,' ');
console.log($scope);<pre id="output"></pre>
如果您有许多(100+)位置,请考虑首先将它们转换为“关联数组”,例如:
validLocations = { "One": 1, "Two": 1 ... etc发布于 2014-09-17 14:34:22
正如Paul S.的评论所暗示的那样,您需要手动遍历:
var locations = [
{ name : "One"},
{ name : "Two"},
{ name : "Three"},
{ name : "India"},
{ name : "Japan"},
{ name : "China"} ];
var tempLocations = [
{ name : "One"},
{ name : "Two"},
{ name : "global"},
];
var newTempLocations = tempLocations.filter(function(temp){
return locations.some(function(location){ // stop and return true at first match
return location.name === temp.name;
});
})
// print output
document.getElementById("output").innerHTML = JSON.stringify(newTempLocations, null, " ");<pre id="output"></pre>
发布于 2014-09-17 16:02:34
如果$scope.locations不会经常更改,您可以执行以下操作:
构建位置查找表
var location_lookup = {};
for ( var i = 0; i < $scope.locations.length; i++ ) {
location_lookup[$scope.locations[i].name] = true;
}基于密钥存在性的过滤器
$scope.filteredLocations = $scope.tempLocations.filter(function(temp) {
return location_lookup.hasOwnProperty(temp.name);
});如果您比重新计算查找所需的筛选频率更高,这将证明要快得多。因此,如果$scope.locations是静态的,这将是一个很好的途径。
我建议不要使用temp.name in location_lookup作为另一张海报,因为这也将检查location_lookup对象的所有原型属性。例如,如果应用程序中的另一个脚本执行了Object.prototype.global = function(){},那么过滤器将返回“全局”作为$scope.locations的一部分,这不是您想要的行为。hasOwnProperty只检查对象本身,而不是任何原型继承,同时也是一种更有效的方法。
小提琴演示:http://jsfiddle.net/cu33ojfy/ (还包括一个使用Array.prototype添加.filter_locations()方法的实现,但向Array.prototype添加通常是个坏主意)
https://stackoverflow.com/questions/25893250
复制相似问题