0

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

  • Possible duplicate of [Iterate through object properties](https://stackoverflow.com/questions/8312459/iterate-through-object-properties) – GalAbra Feb 23 '18 at 21:17

4 Answers4

1

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");
}
void
  • 36,090
  • 8
  • 62
  • 107
0

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);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Niels
  • 48,601
  • 4
  • 62
  • 81
0

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");
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116
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;
}
Eigendrea
  • 320
  • 4
  • 14