문제

What is the correct way to get all objectkeys with a false value in an array like this in Javascript:

[
  { unknownkey1 : false },
  { unknownkey2 : true  },  
  { unknownkey3 : false },
  { unknownkey4 : true  },
  { unknownkey5 : false },
  { unknownkey6 : true  }
]

Result should be an array containg all keys with a false value.

What I want is a cleaner solution for this:

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

    for ( key in results[i] ) {

      if ( results[i].hasOwnProperty( key ) && results[i][key] === false ){

         console.log( key );

      }

    }

}

If the value is not false it contains another object. But they are not needed and I would prefere a way that ignores the child objects if possible.

도움이 되었습니까?

해결책 2

var arr=[
  { unknownkey1 : false },
  { unknownkey2 : true  },  
  { unknownkey3 : false },
  { unknownkey4 : true  },
  { unknownkey5 : false },
  { unknownkey6 : true  }
]

// You can return a key for false values and nothing for true, 
// then filter out the empty indexes:

var falsies= arr.map(function(itm){
    return itm[Object.keys(itm)[0]]==false? Object.keys(itm)[0]:''}).
    filter(Boolean);

/*  returned value: (Array)
unknownkey1,unknownkey3,unknownkey5
*/

다른 팁

You want to iterate through the array, and then iterate through each key in each of those objects, then store those false keys in another array. Pretty straightforward.

var data = [
  { unknownkey1 : false },
  { unknownkey2 : true  },  
  { unknownkey3 : false },
  { unknownkey4 : true  },
  { unknownkey5 : false },
  { unknownkey6 : true  }
];

var keys = [];

data.forEach(function(object) {
    for (var key in object) {
        if (object[key] === false) keys.push(key);
    }
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top