javascriptmetadatagoogle-tag-managermeta-tags

How can I convert a JavaScript array's object and its value into separate attributes of an HTML meta tag?


in the head section I have a js:

var product = {
                ProductID: '97087',
                Thema: '18',
                CategoryID: '49',
                Region1: ['21'],
                Region2: ['35'],
                Region3: [],
                Price: '22,00',
                Brand: 'Brand',
            };

Is there a way to turn the ProductID into a meta tag like

<meta name="brand" content="97087">     

Solution

  • This can be achieved by looping though the keys of the product object and appending it with the associated value to the <head>. The code below will result in:

    <meta name="ProductID" content="97087">
    <meta name="Thema" content="18">
    <meta name="CategoryID" content="49">
    <meta name="Region1" content="21">
    <meta name="Region2" content="35">
    <meta name="Region3" content="">
    <meta name="Price" content="22,00">
    <meta name="Brand" content="Brand">
    

    var product = {
                    ProductID: '97087',
                    Thema: '18',
                    CategoryID: '49',
                    Region1: ['21'],
                    Region2: ['35'],
                    Region3: [],
                    Price: '22,00',
                    Brand: 'Brand',
                };
                
    var metaTags = Object.keys(product).map(function(key) {
      return '<meta name="' + key + '" content="' + product[key] + '">';
    }).join('');
    
    var headElem = document.querySelector('head');
    headElem.innerHTML += metaTags;
    
    
    console.log(headElem.querySelectorAll('meta'));
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Document</title>
    </head>
    <body>
      
    </body>
    </html>