检查 Array 在 Javascript 中是否具有精确的 Key Value 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21538322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:07:15  来源:igfitidea点击:

Check if Array has exact Key Value object in Javascript

javascriptarrays

提问by Spittal

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" }?

如何检查数组是否包含确切的对象 { "key1" : "value2" }?

Thanks for the help.

谢谢您的帮助。

回答by Matt

In modern browsers,

在现代浏览器中,

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

will be trueif pair is found, otherwise false.

true如果对被发现,否则false

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

这假设每个对象只包含一个键/值对,并且该值是 never undefined

回答by talemyn

You first want to check to see if the key exists in the object (using .hasOwnProperty()) ANDif that key values references a "value" value that matches the one that you are looking for. Teh code is pretty straightforward:

您首先要检查对象中是否存在键(使用.hasOwnProperty()以及该键值是否引用了与您要查找的值匹配的“值”值。代码非常简单:

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
    }
}