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 propertiesGalAbra– GalAbra2018年02月23日 21:17:39 +00:00Commented Feb 23, 2018 at 21:17
4 Answers 4
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");
}
4 Comments
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");
Comments
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;
}
Comments
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);