简体   繁体   中英

How do i check that an array contains values of an object

Lets say that we have an object like:

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

and an array:

["00002", "00003"]

What i am trying to do is check Objects values and if that keys values are not all existing in array alert user that key A values are not all existed in array.

What if A is unknown ??

You can do .filter on the array and check if all the values exists in another array or not.

 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"); } 

Update: If you dont know what the key is:

There could be multiple ways, the one I would is to use Object.values(obj)[0] to access the array.

 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"); } 

You should retrieve the array inside the object:

object.A

Next you need to loop through the array you want to check

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);

Or if you need Old Internet Explorer support.

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);

Just loop them and check..

 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"); 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM