1

I have the below code, which loops through the DOM looking for elements that have an id starting with "sale-", with an attribute "data-id", capturing the value, then stripping the opening and closing square brackets - pushing it all into a JSON object:

els = $("div[id^='sale-']");
Array.prototype.forEach.call(els, function(el) {
var id = el.attributes[2].value.replace(/\[|\]/gi, "");

var jsonObject = {"id" :+id};

var myJSON = JSON.stringify(jsonObject);
console.log(myJSON+",")
});

This works and the output is:

enter image description here

Now the problem comes when I want to apply some static JSON code before and after the loop.

I would like something like the below:

// static
dataLayer.push({
  'ecommerce': {
    'impressions': [

// loop portion
{"id":50450},
{"id":49877},
{"id":49848}, 
{"id":49912},
{"id":49860},
{"id":49825}, 
{"id":48291}, 
{"id":49667},

// static
]
  }
});

1 Answer 1

2

Firstly you can make the array creation much more simple by calling map() on the jQuery object. From there you can simply add the resulting array to an object with the required structure. Try this:

var idArr = $("div[id^='sale-']").map(function() {
  var id = this.attributes[2].value.replace(/\[|\]/gi, "");
  return { id: +id };
}).get();

dataLayer.push({
  ecommerce: {
    impressions: idArr
  }
});

Also note that this.attributes[2].value can be improved, but you haven't stated which attribute you're expecting that to target.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.