Utilize a JavaScript array containing numerous objects to transmit information to the Google Tag Manager and populate the Google data

Is there a way to send multiple product information to the Google data layer as an array of objects, rather than just one combined object? I currently have a script that sends all fields in one object, but I need each product to have its own object within the array. Can someone help me achieve this with my code below? Thank you!

$(function () {

        var Container = (".product");

        var itemName = $($(Container)).find(".item-name").text();

        var itemId = $($(Container)).find(".item-id").text();

        var itemPrice = $($(Container)).find(".item-price").text();

        var itemBrand = $($(Container)).find(".item-brand").text();

        var itemCategory = $($(Container)).find(".item-category").text();

        window.dataLayer.push({
            event: 'Ecommerce - Item List Views',
            event_name: 'view_item_list',
            view_item_list: {
                items: [{
                    item_name: itemName,
                    item_id: itemId, 
                    price: itemPrice, 
                    item_brand: itemBrand,
                    item_category: itemCategory, 
                }]
            }
        });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<!-- Product 1 -->
    <div class="product">
        <div class="item-name">
            <h1>Nike blue shoes</h1>
        </div>
        <div class="item-id">
            SKU-3456
        </div>
        <div class="item-price">
            €22.00
        </div>
        <div class="item-brand">
            Nike
        </div>
        <div class="item-category">
            Shoes
        </div>
    </div>
<!-- Product 2 -->
    <div class="product">
        <div class="item-name">
            <h1>Adidas red shoes</h1>
        </div>
        <div class="item-id">
            SKU-4335
        </div>
        <div class="item-price">
            €55.00
        </div>
        <div class="item-brand">
            Adidas
        </div>
        <div class="item-category">
            Shoes
        </div>
    </div>
<!-- Product 3 -->
    <div class="product">
        <div class="item-name">
            <h1>Nike Yellow Sandals</h1>
        </div>
        <div class="item-id">
            SKU-9654
        </div>
        <div class="item-price">
            €11.00
        </div>
        <div class="item-brand">
            Nike
        </div>
        <div class="item-category">
            Sandals
        </div>
    </div>
<!-- Product 4 -->
    <div class="product">
        <div class="item-name">
            <h1>Vans Black Sneakers</h1>
        </div>
        <div class="item-id">
            SKU-362364
        </div>
        <div class="item-price">
            €99.00
        </div>
        <div class="item-brand">
            Vans
        </div>
        <div class="item-category">
            Sneakers
        </div>
    </div>
</div>

Answer №1

If you're not ready to push right away, consider storing the object in a variable first:

let productObj = {
    event: 'Ecommerce - Item List Views',
    event_name: 'view_item_list',
    view_item_list: {
        items: [{
            item_name: productName,
            item_id: productId, 
            price: productPrice, 
            item_brand: productBrand,
            item_category: productCategory, 
        }]
    }
}

You have the flexibility to add more details as needed:

productObj.view_item_list.items.push({
  item_name:'another item',
  item_id:'asdqwe',price:"20", 
  item_brand:"bar", 
  item_category:"baz"
});

When you've finished adding products to the items array, go ahead and push the entire object:

window.dataLayer.push(productObj);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Managing AJAX requests using Express JS

Currently facing an issue with handling ajax requests using ExpressJS. Whenever I click on an anchor tag, the entire page reloads instead of handling the ajax request on the client side. I am looking to ensure that clicking on any of these links triggers ...

Is it possible to utilize Dictionaries (key, value) collections with JQuery?

Is jQuery capable of supporting a collection of Dictionaries which consists of keys and values? I am interested in organizing the following data into a structured format: [1, false] [2, true] [3, false] This structure should allow for adding, looking up ...

Establish a new <section> to serve as a distinct webpage

I have a question about creating multiple <section> elements on a page. I am looking to build an HTML document with several <section> tags, as outlined below. <html> <head> </head> <body> <sectio ...

Outputting multiple rows from an array

I have a code snippet that scrapes two values from a webpage and stores them in an array. Currently, I can only print the first row of the array and not the entire thing. I believe I need to implement some kind of loop, but my attempts so far have been un ...

Using Template Literals to Log Arrays with Multiple Dimensions

Is there a way to use Template Literals to console.log() a multidimensional array without it being converted into a string? This example demonstrates the difference between logging an array with and without Template Literals: const multidimensionalArray ...

Modifying the maximum length of input fields in HTML, Javascript, and PHP is possible by adjusting the value through

Hi there, I'm facing an issue that should be easy for you guys to help me with. I recently discovered a security flaw while using the maxlength function in HTML. Users can easily modify the maxlength attribute by inspecting elements on the website, wh ...

Incorporating interactive maps into an AngularJS web application

I've been attempting to integrate Google Maps into my AngularJS application, using the script tag below: <script src="https://maps.googleapis.com/maps/api/js?key=[MySecretKeyHere]&callback=initMap" async defer></script> I found this ...

Securing user access in react-native with redux and asyncStorage

As a newcomer to React Native and React Redux, I am currently working on a project that involves implementing authentication and authorization. The goal is to display a splash screen for a few milliseconds, then redirect the user to either the login page ...

Eliminate elements from a collection of structures

There is a structure defined as follows: typedef struct score_entry { char name[21]; int score; } score_entry; Additionally, there is an array declared as: score_entry readin[1000]; A function needs to be created that takes in a score_entry ...

What could be causing my jQuery event handler to not work properly when connected to numerous elements?

I have implemented jquery to dynamically add multiple "addTask" form elements to a "ul" on the webpage every time a link is clicked. $('span a').click(function(e){ e.preventDefault(); $('<li>\ <ul>\ ...

What is the correct way to include a variable such as /variable/ in a MongoDB query?

I need help passing in a searchTerm from a variable, what is the best way to do this? const mongoquery = { description: { $in: [ /searchTerm/ ] } }; I attempted it like this initially: const mongoquery = { description: { $in: [ `/${searchTerm}/` ] } }; H ...

What is causing React Js to fail loading css when switching from anchor tag to link tag?

I am learning React and experimenting with creating a basic static website using HTML templates in version ^18.2.0 of React JS. Everything seems to be functioning correctly, however, I have encountered an issue with page refresh. Specifically, when I repla ...

Converting image bytes to base64 in React Native: A step-by-step guide

When requesting the product image from the backend, I want to show it to the user. The issue is: the API response contains a PNG image if the product has an image, but returns a (204 NO Content) if the product does not have an image. So, I need to display ...

What is the best way to manage uploading images with varying proportions in React Js?

I've been scouring the internet for the best way to upload images of varying sizes (width and height) while still being able to display them neatly in a gallery format. An ideal example is the Facebook gallery, where all the pictures are perfectly al ...

Utilizing Regex to Authenticate a CAGE Code

Our task is to create a RegEx pattern that can accurately validate a CAGE Code A CAGE Code consists of five (5) positions. The code must adhere to the following format: The first and fifth positions must be numeric. The second, third, and fourth position ...

Standardized Object and Array Structures in MongoDB

[ { "data": { "id": "123", "name": "delta1" }, "property_data": [ { "ser_name": "Insights", "ser_value": "10000&qu ...

Instructions on removing an HTML element from a div that has the attribute contentEditable

Here is an example of HTML code: <div id="editable" contentEditable="true"> <span contentEditable="false">Text to remove</span> </div> I want to be able to delete the entire span element (along with its text) with just one bac ...

methods to retrieve value from a javascript function

Just a quick inquiry - what's the best way to pass or return a value from a function? Here is my code: function numberOfDivs(){ var numberOfElements = $("#div").children().length; // Counting the number of existing divs return numberOfElements; } ...

Placing buttons on top of a video within a div container

I am facing a challenge with implementing custom controls on a video embedded in my webpage. I have tried setting a div to absolute position for the buttons, but they are not clickable. Is there a way to achieve this without using jQuery? I need the butto ...

The interface 'children: string' does not share any properties with the type 'IntrinsicAttributes'.ts(2559)

When I export the component, the value from the input email does not appear as a VALUE property. How can I collect the text written in this exported component in my code? NOTE: I am working on developing a design system using STORYBOOK. export const Login ...