Currently, I have a JavaScript code snippet where I am attempting to create a promotion
field within each of my promotion items. However, I am encountering an issue where it keeps nesting itself endlessly, whereas I only require it to contain one reference (refer to the screenshot)
I have attempted to implement a check to verify if promotion.promotion
already exists and if so, continue with the loop. Unfortunately, this solution does not seem to execute as expected.
What could be the missing piece in my code?
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
}
For a demonstration, you can visit this jsfiddle link.
https://i.sstatic.net/Qca1v.png
The desired output structure is as follows:
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',
}
}]