Home > Net >  Check if a property of an object is present in an array
Check if a property of an object is present in an array

Time:11-26

I want to create a script (for Google Tag Manager) that checks if an object's property is present in an array:

var array1 = [X, Y, Z]

var array2 = 
[
{item1=value1,item2=value2,item3=value3},
{item1=value1,item2=value2,item3=value3}
]

var total = 0;

If property 1 of the object is present in array 1, then we add property 2 in a variable to calculate the total

Here is my code but I think my logic is not good :

 var array1 = array1;
  var array2 = array2;
  var amount = 0;
  
  for(var i=0; i<array2.length; i  ) {
    var propertyTarget = array2[i].item1
    if(propertyTarget === array1[i]) {
        total  = array2[i].item2;

I also tested:

  for (var i = 0; i < array2.length; i  ) {
    
    for (var j = 0; j < array1.length; j  ) {
    
      if(array2[i].item1 === array1[j]) {
        total  = array2[i].item2;

I have read on other discussions that it is also possible to use filter or include but without success...

Your help would be very helpful

  • Related