我在数组中有如下记录:
$scope.skills = [];
$scope.skills['et']= s1
$scope.skills['et']= s2
$scope.skills['et']= s3
$scope.skills['gf']= t1
$scope.skills['gf']= t2
$scope.skills['gf']= t3
$scope.skills['po']= b1
$scope.skills['po']= b2
$scope.skills['po']= b3
现在我想根据以下值从数组中删除所有记录:
$scope.value ='gf';
现在我想从索引不是'gf'的数组中删除所有记录:
所以技能数组应该只包含'gf'的记录,如下所示:
预期产出:
$scope.skills['gf']= t1
$scope.skills['gf']= t2
$scope.skills['gf']= t3
答案 0 :(得分:1)
您应该能够循环遍历数组对象中的所有键,并删除您不想要的键。
for(var k in Object.keys($scope.skills)){
if(k !== "gf"){
delete $scope.skills[k];
}
}
作为每个键分配的旁注,您将在以下
之后覆盖该值$scope.skills['gf']= t1
$scope.skills['gf']= t2
$scope.skills['gf']= t3
$scope.skills['gf']
的值将是变量t3
的值。
答案 1 :(得分:0)
我认为你的例子存在概念上的错误。将多个值分配给同一属性将覆盖先前的分配。
无论如何,如果您只需要来自对象的单个属性,则可以使用该属性创建一个新对象:
$scope.skills = $scope.skills['gf'];
答案 2 :(得分:0)
您需要更改“数组”的结构,以便能够使用相同的密钥存储多个项目。
示例:
$scope.skills = [];
$scope.skills.push({key: 'et', value: 's1'});
$scope.skills.push({key: 'et', value: 's2'});
$scope.skills.push({key: 'et', value: 's3'});
$scope.skills.push({key: 'gf', value: 't1'});
$scope.skills.push({key: 'gf', value: 't2'});
$scope.skills.push({key: 'gf', value: 't3'});
$scope.skills.push({key: 'po', value: 'b1'});
$scope.skills.push({key: 'po', value: 'b2'});
$scope.skills.push({key: 'po', value: 'b3'});
现在你可以这样删除:
$scope.keyToDelete = 'gf';
for(var i = $scope.skills.length - 1; i >= 0; i--) {
if($scope.skills[i].key === $scope.keyToDelete) {
$scope.skills.splice(i, 1);
}
});