从值为真的对象中获取正数

时间:2016-02-14 12:24:24

标签: javascript

我该如何解析这个对象?

$scope.selectedCountries = {2: true, 3: true, 4: true, 5: true, 7: true, 8: true, 9: true, 10: false, 11: true, 13: true, 14: true, 15: true, 17: true, 18: false, 19: true, 20: false, 21: true, 22: false, 23: true, 24: false, 25: false, 26: false};

我已经尝试过forEach,数组位置为[1]或[0]等......

我想获取值为true的所有数字,并将其作为数组值存储在变量

示例:

var ids = [2,3,4,5,7,8,9,11,13,14,15,17,18,21,23]

4 个答案:

答案 0 :(得分:1)

您可以使用Object.keys来使用get属性名称,并按以下方式对其进行过滤:

var selectedCountries = {2: true, 3: true, 4: true, 5: true, 7: true, 8: true, 9: true, 10: false, 11: true, 13: true, 14: true, 15: true, 17: true, 18: false, 19: true, 20: false, 21: true, 22: false, 23: true, 24: false, 25: false, 26: false};

var ids = Object.keys(selectedCountries).filter(function(key) {
    return selectedCountries[key];
});

答案 1 :(得分:1)

使用Object.keys(selectedCountries)获取对象中的键数组,然后循环遍历该新数组:

$scope.ids = []; //initialise ids as an array
$scope.selectedCountries = {2: true, 3: true, 4: true, 5: true, 7: true, 8: true, 9: true, 10: false, 11: true, 13: true, 14: true, 15: true, 17: true, 18: false, 19: true, 20: false, 21: true, 22: false, 23: true, 24: false, 25: false, 26: false};
var keys = Object.keys($scope.selectedCountries);//get a list of all keys in selectedCountries

keys.forEach(function(k) { //loop through all keys 
    if ($scope.selectedCountries[k]) { //if the value for that key in selectedCountries is true
        $scope.ids.push(k); //push it to ids
    }
});

答案 2 :(得分:1)

您可以通过以下for循环获得所需的结果:

var $scope = {'selectedCountries': {2: true, 3: true, 4: true, 5: true, 7: true, 8: true, 9: true, 10: false, 11: true, 13: true, 14: true, 15: true, 17: true, 18: false, 19: true, 20: false, 21: true, 22: false, 23: true, 24: false, 25: false, 26: false}};

var results = [];
for (key in $scope.selectedCountries){
    if ($scope.selectedCountries[key]) {
      results.push(parseInt(key));
}}
console.log(results)

祝你好运!

答案 3 :(得分:1)

如果要迭代对象的键,请使用for in表达式。至于你的情况:

var selectedCountries = {2: true, 3: true, 4: true, 5: true, 7: true, 8: true, 9: true, 10: false, 11: true, 13: true, 14: true, 15: true, 17: true, 18: false, 19: true, 20: false, 21: true, 22: false, 23: true, 24: false, 25: false, 26: false};  
var ids = [];
for(key in selectedCountries) {
    if (selectedCountries[key]) {
        ids.push(+key)
    } 
}
console.log(ids);

你会得到阵列。请注意,此arr.push(+key)+将执行与Number()相同的工作。