0

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

Criquet
  • 1
  • 1

2 Answers2

0

Try this:

array2.forEach(obj => {
  array1.forEach(prop => {
   if(obj.hasOwn(prop)) {
    // ... do something
     }
  })
})
    
cucumber
  • 57
  • 5
  • You cannot use the arrow functions on Google Tag Manager... But I will look at the doc on foreach – Criquet Nov 25 '22 at 16:37
  • Ok, sorry didn't know about that. But this still can be done without arrow functions. You can do it in a for loop as you did, just instead if(array2[i].item1 === array1[j]) should be: if (array2[i].hasOwn(array1[j])) – cucumber Nov 25 '22 at 16:55
  • if (array2[i].hasOwn(array1[j])) --- I do not need to indicate the property of the object? – Criquet Nov 25 '22 at 17:20
  • I am not sure if I understand your question. If array1 is array of property names, and array2 is array of objects, and you want to check if property name exists on the object from array2, than no. But if both arrays (array1 and array2) are arrays of objects than it's a different thing. – cucumber Nov 25 '22 at 19:02
  • Array 1 is an array with only numbers Array 2 is an array that embeds objects. Array 2 is obtained when a user places an order, it is the datalayer of GTM which reports all the products purchased with the properties: price, id, category id, etc... I want to check if one of the products purchased corresponds to one of the categories in my table 1 (if product ID Category === ID Category of the array1). – Criquet Nov 28 '22 at 08:14
0

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