简体   繁体   中英

Creating JSON - part loop, part plain string

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:

在此处输入图片说明

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
]
  }
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM