I have some javascript where I’m trying to create a promotion within each of my promotion items. Right now though, for some reason it keeps on nesting itself indefinitely, and I only need it to contain one reference (see screenshot)
I’ve tried adding a check to see if promotion.promotion already exists and if it does to continue, but this just doesn’t seem to run.
What am I missing?
const promotions = [{
title: 'My offer title',
subtitle: 'lorem ipsum'
}, {
title: 'My offer title 2',
subtitle: 'lorem ipsum'
}, {
title: 'My offer title 3',
subtitle: 'lorem ipsum'
}]
for (const [index, promotion] of promotions.entries()) {
if (promotion.promotion) continue
promotion['promotion'] = promotion
}
Here’s a jsfiddle for a demo.
This is what I need for the output:
const promotions = [{
title: 'My offer title',
subtitle: 'lorem ipsum',
promotion: {
title: 'My offer title',
subtitle: 'lorem ipsum',
}
}, {
title: 'My offer title 2',
subtitle: 'lorem ipsum',
promotion: {
title: 'My offer title 2',
subtitle: 'lorem ipsum',
}
}, {
title: 'My offer title 3',
subtitle: 'lorem ipsum',
promotion: {
title: 'My offer title 3',
subtitle: 'lorem ipsum',
}
}]
Advertisement
Answer
for (const [index, promotion] of promotions.entries()) {
if (promotion.promotion) continue
promotion.promotion = { ...promotion}
}
