In Javascript, the assignment of a custom property continues indefinitely instead of occurring just once

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

Answer №1

Iterating through each element in the 'promotions' array and checking if a promotion exists. If not, creating a new one based on the existing data.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display the accurate prompt in the event of 2 `catch` statements

elementX.isPresent() .then(() => { elementX.all(by.cssContainingText('option', text)).click() .catch(error => { throw {message: "Unable to select text in dropdown box"} ...

angular data binding returning the identifier instead of the content

I have been dealing with managed fields retrieved from a web server in the following format: { "fields":{ "relationshipStatus":[ { "fieldId":4, "name":"Committed" }, { "fieldId":2, ...

Looking for a Search Field that clears default text when focused - Compatible with Firefox 3.6?

I have attempted various jQuery and JavaScript solutions found on this page: How to clear text field on focus of text field Surprisingly, all of the solutions work except for FF 3.6. So, I am wondering, What alternative can I use to make this feature com ...

Transferring a basic PHP date variable to JavaScript

Here is my PHP code snippet: <?php $mytestdate = "Oct 23, 2019 20:00:00"; ?> I'm facing an issue with this JavaScript code: <script> var mydate = "<?php echo $mytestdate; ?>"; // Set the date we're counting down to var countD ...

Close popup after submitting the form

On my website, I have a function to submit a form within a modal. Everything works well except for when I uncomment a certain line of code. When I uncomment that line, my test mysql insert on the page /index.php/trainings/add doesn't get executed. I a ...

What is the method for modifying the array that has been generated using Vue's "prop" feature?

According to the Vue documentation, a prop is passed in as a raw value that may need transformation. The recommended approach is to define a computed property using the prop's value. If the "prop" is an array of objects, how can it be transformed int ...

Creating a customized greeting message using discord.js

I've been working on creating a Discord bot using discord.js, and I'm trying to figure out how to make the bot send a welcome message when a new member joins the server and opens a chat with the bot. The message should be something like "Hi there ...

Loading local JSON data using Select2 with multiple keys can greatly enhance the functionality

Comparing the select2 examples, it is evident that the "loading remote data" example contains more information in the response json compared to the "loading array data" example. I am interested in knowing if it is feasible to load a local json file with a ...

Experiencing a problem when attempting to activate the html5 mode feature in AngularJS to eliminate the #

I've been scouring through various sources like stackoverflow and the web, but I haven't found a clear answer to my question. Can someone please help me out? Here's what I'm struggling with: In my AngularJS application, I enabled &apos ...

Pressing a button within an HTML table to retrieve the corresponding value in that row

How can I click a button inside an HTML table, get the value on the same row and pass it to an input field called FullName? Thanks for your help! <td><?php echo $r['signatoryname'] ?></td> <td ...

The functionality of Angular bootstrap scrollspy is hindered when dealing with dynamically changing image content

I recently came across an answer that guided me to fork an example for implementing scrollspy in Angular.js. My goal is to populate dynamic content using a template that includes images. You can find the example here: http://plnkr.co/edit/OKrzSr Here are ...

Load components in NextJS lazily without utilizing `next/dynamic`

Currently, I am in the process of developing a component (Editor) that should always be lazy-loaded in React applications. However, I need it to be compatible with any React app. While I have successfully implemented lazy loading with Create React App usi ...

What is a reliable method to retrieve the text from the current LI if all LI elements in the list share the

I'm encountering an issue with retrieving the text from LI elements because I have 10 list items and they all have the same class name. When I attempt to fetch the text using the class name or id, I only get the text of the last item. Here is my code ...

Combine two scope arrays in AngularJS

Is there a way to merge two arrays of scope in AngularJS within my controller so that I can display them in a single table? The merging would be based on a common field present in both arrays, similar to an SQL join operation where data from both tables ...

Is it feasible to use PHP code within a Javascript environment?

Looking for help with integrating PHP code into a JavaScript script: var bigData = { "teams" : [], "results" : [] }; for( var i=1 ; i<16 ; i+=2 ) { bigData.teams.push(["<?php echo 1; ?>",'Team '+(i+1)]); } for( var j=1 ; j& ...

Converting a JavaScript function to TypeScript with class-like variables inside: a step-by-step guide

During the process of converting a codebase to TypeScript, I encountered something unfamiliar. In particular, there are two functions with what appear to be class-like variables within them. The following function is one that caught my attention: const wai ...

HTML5 allows users to choose data from a list using a ComboBox and submit the 3-digit code

I'm looking to enhance my form by including an input box where users can select airports, similar to the functionality on this website (). When typing in the Destination Input, I want users to see a list of possible values with detailed suggestions su ...

The jquery selector fails to retrieve all elements

On the upcoming web page, I am attempting to use Jquery to select all <li> elements. Specifically, I want to target all the products contained within <ul class=search-result-gridview-items">. You can find the products here: I have made attempt ...

Encountering an ongoing problem with trial repetition in JsPsych, which is causing the looping to continue endlessly without

As a beginner in JsPsych, I'm diving into creating a basic math quiz task to sharpen my skills. The goal is to generate random math questions as prompts and stop the task after 10 correct answers. I've managed to code that selects random math pro ...

Encountered an issue with using multer as middleware in Express 4

const express = require('express'); const router = express.Router(), const multer = require('multer'); const uploadFile = multer({ dest: __dirname + '../public/uploads/' }) router.post('/upload', uploadFile, fun ...