Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript assigning custom property keeps assigning indefinitely deep instead of once

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

enter image description here

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',
  }
}]

>Solution :

for (const [index, promotion] of promotions.entries()) {
    if (promotion.promotion) continue
  promotion.promotion = { ...promotion}
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading