javascriptgoogle-datalayer

dataLayer: get arrays objects with specific value


I have a simple JS script that may count values from "price" from each product if the "brand" is equal to "Krups".

Now I am stuck on finding these objects in the data layer which have brand equals to "Krups".

I'm getting errors and can't get objects with products in brand Krupms.

Is there any option how I can get into the array of all objects which have key "brand" equal to "Krups"?

My dataLayer:

enter image description here

My Script:

function getFromDataLayer(key) { 
    let result = null; 
    dataLayer.push(function() { 
        let value = this.get(key);
        if (value) {
            result = value;
        }
    });
    return result;    
};
    
const ecom = getFromDataLayer('ecommerce')

if (ecom.filter(function(e) { return e.brand === 'Krups'; }).length > 0) {
  console.log(this)
}

Solution

  • you can try this

    if (ecom?.purchase?.products?.filter(function(e) { return e.brand === 'Krumps'; }).length > 0) {
      console.log(this)
    }