Check if a property of an object is present in an array

284 views Asked by At

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

2

There are 2 answers

5
cucumber On

Try this:

array2.forEach(obj => {
  array1.forEach(prop => {
   if(obj.hasOwn(prop)) {
    // ... do something
     }
  })
})
    
2
SHERAWAT LOKESH On

i can't understand what you want if you want to check if it's type is object then you should use Typeof to check