I have an object, where I want to:
- Loop through the object
- To check if any of the values === 0
- 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();
});
}
}
} + ')();';