Make sure the array has a Key Value object in Javascript

I am doing a simple check to see if this array has an exact pair of key values.

eg

testArray = [ { "key1": "value1" }, { "key2": "value2" }, { "key1": "value2" ) ] 

How to check if an array contains the exact object {"key1": "value2"}?

Thanks for the help.

+7
javascript arrays
source share
2 answers

In modern browsers

 testArray.some(function(o){return o["key1"] === "value2";}) 

will be true if a pair is found, false otherwise.

This assumes that each object contains only one key / value pair and that the value is never undefined .

+15
source share

First you want to check if a key exists in the object (using .hasOwnProperty() ) And , if the values โ€‹โ€‹of this key refer to the value "value" corresponding to the one you are looking for, the code is pretty simple:

 var testKey = "some_key"; var testVal = "some_val"; for (i=0; i < testArray.length; i++) { if ((testArray[i].hasOwnProperty(testKey)) && (testArray[i][testKey] === testVal)) { // positive test logic break; // so that it doesn't keep looping, after finding a match } else { // negative test logic } } 
0
source share

All Articles