我正在尝试将数据推入对象内的数组。数组是对象的数组(在代码中更清楚)。
主要代码有效,它可以正确分割有效负载,但是主要ecommObj不能正确输出数组。
请帮助。
我尝试使用concat,push,push.apply,最后我在其中留下了“ =”。我只是个主意。
var siteMerch = [
{"placement": "homepage","position": "T1","campaignName": "poloshirts","campaignStartDate": "12-08-19"},
{"placement": "homepage","position": "T2","campaignName": "groomingbestsellers","campaignStartDate": "12-08-19"},
{"placement": "homepage","position": "T3","campaignName": "journalhowtobuyasuitonline","campaignStartDate": "12-08-19"},
{"placement": "homepage","position": "WN","campaignName": "newarrivals","campaignStartDate": "12-08-19"},
{"placement": "homepage","position": "C1","campaignName": "fourwaystorunbetter","campaignStartDate": "15-08-19"},
{"placement": "homepage","position": "M1","campaignName": "mrpcap8tshirts","campaignStartDate": "12-08-19"},
{"placement": "homepage","position": "T1","campaignName": "poloshirts","campaignStartDate": "12-08-19"},
{"placement": "homepage","position": "T2","campaignName": "groomingbestsellers","campaignStartDate": "12-08-19"},
{"placement": "homepage","position": "T3","campaignName": "journalhowtobuyasuitonline","campaignStartDate": "12-08-19"},
{"placement": "homepage","position": "WN","campaignName": "newarrivals","campaignStartDate": "12-08-19"},
{"placement": "homepage","position": "C1","campaignName": "fourwaystorunbetter","campaignStartDate": "15-08-19"},
{"placement": "homepage","position": "M1","campaignName": "mrpcap8tshirts","campaignStartDate": "12-08-19"}
];
var payLoad = 5;
var del = "-_-";
var chunk = [];
var promotions = siteMerch.map(function(i){
let promotion = {
'id':i.placement + del + i.campaignName + del + i.campaignStartDate + del + i.position,
'name':i.campaignName + " - " + i.campaignStartDate,
'creative':i.placement,
'position':i.position
}
return promotion;
})
var ecommObj = {
event: 'EEC Promo View',
ecommerce: {
promoView: {
promotions: []
}
}
};
while (promotions.length) {
chunk = promotions.splice(0,payLoad);
ecommObj.ecommerce.promoView.promotions = chunk; //The issue is HERE.
console.log(ecommObj); //This will be a dataLayer push later on, I'm just checking it first
ecommObj.ecommerce.promoView.promotions.length = 0;
}
我希望我的ecommObj.ecommerce.promoView.promotions
在那里包含5个对象的有效载荷,但是当前控制台显示输出具有空白数组。
答案 0 :(得分:0)
您的代码运行正常。您认为是其他原因,因为在控制台中通过浏览对象检查器来检索数组时,该数组已更改。
替换
console.log(ecommObj);
使用
console.log(ecommObj.ecommerce.promoView.promotions);
或
console.log(JSON.stringify(ecommObj));
,您会看到它有效。
顺便说一下,promotions: []
和ecommObj.ecommerce.promoView.promotions.length = 0;
都是不需要的,可以删除。