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