如何检查数组是否包含对象的值

时间:2018-02-23 21:11:05

标签: javascript

让我们说我们有一个像这样的对象:

{"A":["00002","00003","00004"]}

和一个数组:

["00002", "00003"]

我要做的是检查对象值,如果这些键值不是全部存在于数组警告用户中,则键A值不是全部存在于数组中。

如果A未知怎么办?

4 个答案:

答案 0 :(得分:1)

您可以对阵列执行.filter并检查是否所有值都存在于另一个阵列中。

var obj = {"A":["00002","00003","00004"]}
var check = ["00002", "00003"];

if(obj.A.filter(el => !check.includes(el)).length){
  console.log("Some elements does not exists");
}

更新:如果您不知道密钥是什么:

可能有多种方式,我可以使用Object.values(obj)[0]来访问数组。

var obj = {"A":["00002","00003","00004"]}
var check = ["00002", "00003"];

if(Object.values(obj)[0].filter(el => !check.includes(el)).length){
  console.log("Some elements does not exists");
}

答案 1 :(得分:0)

您应该检索对象内的数组:

object.A

接下来,您需要遍历要检查的数组

var allMatch = true;
var object = {"A":["00002","00003","00004"]};
["00002", "00003"].forEach(function(item){
    if(object.A.indexOf(item) === -1){ // -1 when not found
        allMatch = false;
    }
});

alert("Do they all match? " + allMatch);

或者如果您需要旧的Internet Explorer支持。

var allMatch = true;
var object = {"A":["00002","00003","00004"]};
var arr = ["00002", "00003"];
for(var i=0;i<arr.length;i++){
    if(object.A.indexOf(arr[i]) === -1){ // -1 when not found
        allMatch = false;
        break; // Stop for loop, since it is false anyway
    }
};

alert("Do they all match? " + allMatch);

答案 2 :(得分:0)

只需循环它们并检查..

var haystack = {"A":["00002","00003","00004"]};
var needle = ["00002", "00003"];

function allItemsExist(h, n){
  for(var k in h) if(!~n.indexOf(h[k])) return false;
  return true;
}

if(!allItemsExist(haystack.A, needle)) alert("something is missing");
else alert("everything is here");

答案 3 :(得分:0)

function containsAllData(obj, key, arr)
{
   if(arr.length < obj[key].length)
   {
      alert("Array is not fully contained!");
      return false;
   }
   for(var i = 0; i < obj[key].length; i++)
      if(arr[i] !== obj[key][i])
      {   
         alert("Array contains different data!");
         return false;
      }
   return true;
}