Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Array has exact Key Value object in Javascript

I'm doing a simple check to see if this array has an exact key value pair.

for example

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

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

Thanks for the help.

like image 835
Spittal Avatar asked Feb 03 '14 21:02

Spittal


1 Answers

In modern browsers,

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

will be true if pair is found, otherwise false.

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

like image 59
Matt Avatar answered Oct 24 '22 03:10

Matt