0

I have an object, where I want to:

  1. Loop through the object
  2. To check if any of the values === 0
  3. And then inject this key value only, into my DOM.

However, when I loop through my object, the value is injected into the DOM twice, (probably because there are two key/values in the object). But I only want this to be inject once, as there is clearly only one key, with the value === 0.

(The other === 1)

Here's an example:

window.gaData['UA-123'].experiments = {
  TestA: "1"
  TestB: "0"
}

And this is how I am looping:

 Object.keys(window.gaData["UA-123"].experiments).forEach(function(key, value) {
    if (window.gaData["UA-123"].experiments[key] == 0) {

      console.log(`${key}: ${value}`);

      result += `
        <div>
          <p value="${key}">${key}:Test: ${key} is set to value: ${value}</p>
        </div>
        `
      document.getElementById('container').innerHTML = result;
    }
  });

What am I doing wrong?

In my DOM, I would see:

"Test: TestB is set to value: 0"
"Test: TestB is set to value: 0"

Instead of just once.

If my object grows and more than one key, has the value 0, then of course, I would want to display these too.

But so far, I do not want to display my value twice in the DOM.

Thanks.

I'm creating a chrome extension, so here's the full code:

var actualCode = '(' + function() {
  var dataLayer = window.dataLayer;
  console.log('WINDOW', window);
  // console.log('DATALAYER', dataLayer);

  let result = '';

 Object.keys(window.gaData["UA-123"].experiments).forEach(function(key, value) {
if (window.gaData["UA-123"].experiments[key] == 0) {

  console.log(`${key}: ${value}`);

  result += `
    <div>
      <p value="${key}">${key}:Test: ${key} is set to value: ${value}</p>
    </div>
    `
  document.getElementById('container').innerHTML = result;
  }
 });

  if (dataLayer.ABTest) {
    console.log('True');

    if (dataLayer.ABTest.test) {
        console.log(dataLayer.ABTest.test);

        result += `
          <div class="container">
            <p>Date Launched: ${dataLayer.animal.test.date}</p>
            <p>Test ID: ${dataLayer.animal.test.id}</p>
            <p>Test Description: ${dataLayer.animal.test.name}</p>
            <p>Variant Active: ${dataLayer.animal.test.variant}</p>
            <button id="${dataLayer.animal.test.id}">Switch variant</button>
          </div>
          `
        document.getElementById('container').insertAdjacentHTML('beforeend', result);
        document.getElementById(dataLayer.animal.test.id).addEventListener('click', function() {
          console.log('clicked!')
          // Delete
          window.document.cookie = '_gaexp=COOKIE-1; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; domain=.abc.co.uk'
          // Add
          window.document.cookie = '_gaexp=COOKIE-2; expires=Fri, 19 Jun 2020 20:47:11 UTC; path=/; domain=.abc.co.uk'
          window.location.reload(); 
      });
    }
  }
} + ')();';
Reena Verma
  • 1,617
  • 2
  • 20
  • 47
  • 1
    `function(key, value) { ... }` - that's not what `.forEach()` passes as arguments to the callback. It's (in your case) `(key, index, array)` – Andreas Jun 09 '20 at 12:53
  • After fixing all syntax errors and adding the missing variables your script works as requested -> https://jsfiddle.net/u8t6d9va/ – Andreas Jun 09 '20 at 12:59
  • https://jsbin.com/vorujojiwa/edit?html,js,console,output I think it works as expected – Isa Jun 09 '20 at 13:03
  • Hope this is what you want https://codepen.io/Maniraj_Murugan/pen/YzwyMdb – Maniraj Murugan Jun 09 '20 at 13:07
  • From where `result` is getting initialized. – Zain Ul Abideen Jun 09 '20 at 13:23
  • @ZainUlAbideen I'm creating a chrome extension, so I'll paste the full code above. – Reena Verma Jun 09 '20 at 16:34
  • @Andreas - Strange, this still give me the same output... I moved my block of code further down my script, to see if that would make a difference and it returned the following instead: ``"Test: TestB is set to value: 0" "Test: TestB is set to value: 1"`` I think i might try injecting in a brand new container instead. Maybe there is a clash, as I'm injecting object data twice in the same DOM element. – Reena Verma Jun 09 '20 at 16:42

1 Answers1

1

replace this:

if (window.gaData["UA-123"].experiments[key] == 0) {

with this:

if (window.gaData["UA-123"].experiments[key] == "0") {

Your data contains strings, not integers.

Paul Nikonowicz
  • 3,883
  • 21
  • 39