Insert an array containing objects into another array nested within an object

I'm struggling to insert data into an array within an object. The array consists of objects, as seen in the code below.

The main part of the code is functioning properly, it properly splits my payload. However, the main ecommObj is not displaying the array correctly.

I have tried using concat, push, push.apply and even leaving an "=" in there. I am running out of ideas.

  var siteMerch = [
  // List of site merch here
  ];

  var payLoad = 5;
  var del = "-_-";
  var chunk = [];
  var promotions = siteMerch.map(function(i){
  let promotion = {
      // Promotion object details here
  }
  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;
  }

I'd like the

ecommObj.ecommerce.promoView.promotions
to hold payloads of 5 objects each, but currently, the console displays an empty array.

Answer №1

Your code is functioning properly. The confusion may arise when you inspect the array through the object inspector in the console, as it might have changed by then.

Instead of

console.log(ecommObj);

try using

console.log(ecommObj.ecommerce.promoView.promotions);

or

console.log(JSON.stringify(ecommObj));

This should show that your code is indeed working correctly.


Additionally, promotions: [] and

ecommObj.ecommerce.promoView.promotions.length = 0;
are not necessary and can be removed.

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

The JavaScript class failed to work properly within the asp.net framework

I have successfully implemented a JavaScript function on my aspx page. Here is the code snippet: <script type="text/javascript"> $(document).ready(function () { console.log("ready!"); var options = []; var ...

Ways to apply CSS to a changing div ID

I am looking to apply CSS to a dynamically generated div ID. var status = var status = item.down().next().innerHtml(); if(status == "test") { var c = 'item_'+i ; c.style.backgroundColor = 'rgb(255, 125, 115)'; //'ite ...

Axios - Show the error message returned from validation as [object Object]

Within my API, I include the following validation logic: $request->validate([ 'firstname' => 'required', 'lastname' => 'required', 'username' => 'required|unique:us ...

What is the best way to pass only the second parameter to a function in TypeScript?

Let's consider a TypeScript function as shown below: openMultipleAddFormModal(commission?: Commission, people?: People): void { // some data } To make a parameter optional, I have added the Optional Chaining operator. Now, how can I modify the code ...

Ways to activate JavaScript on a completely dynamic AJAX ASP.NET website

Encountering a dilemma: I have developed a fully dynamic site with only one update panel on the startpage. All content is generated dynamically through code behind, with different pages as web user controls. The issue arises when attempting to open two d ...

After encountering a character with CSS, begin a new line

I have a CSV spreadsheet with data that looks like this: <p>Features:• first feature• second feature• third feature• fourth feature• and so on (the total number of features is variable)</p> I want each feature to display on a new li ...

Collapsing Bootstrap menu bar causing logo overlap

When the navbar collapses (when it shows the toggle icon), the menu items (home, services, portfolio, about, contact) overlap with the logo. If I remove the position:absolute from the logo (navbar-brand), the menu appears in the center. Is there a way to h ...

Tips for Including a Parallax Image Within a Parallax Section

Currently, I am working on implementing a parallax effect that involves having one image nested inside another, both of which will move at different speeds. My progress has been somewhat successful, however, the effect seems to only work on screens narrowe ...

How to Retrieve an Image from Byte Array in Java AWS Lambda API Response

I am having some trouble downloading an image file (001.jpg) from my AWS S3 bucket using Java. I have included a code snippet below that handles the downloading process. if (StringUtils.isNotEmpty(s3Key)) { AmazonS3Connector s3 = AmazonS3Connector. ...

access the return value of a jQuery function within another function

I'm struggling to retrieve a value from this function, I suspect it may be due to the nested functions. (ps. I am aware that I do not need to use quotes when retrieving a BOOL value) Any assistance would be greatly appreciated. $(document).ready(fu ...

my initial attempt at using Firebase cloud functions

I'm currently attempting to create my first Firebase Cloud Function. My goal is to take the value of the 'name' field from the 'amr' document and add it to the 'ahmed' document under a new field called 'newName' ...

Connecting Ember controllers with views/elements

As a developer with an Angular background, I am relatively new to Ember. Let's consider a scenario where there are multiple elements, each containing different sets of data. #elem1 10 #elem2 20 #elem3 30 My objective is to link each of these indiv ...

What is the best way to add a listener for a modification of innerHTML within a <span>?

How can I detect changes inside a particular <span> element in order to attach a handler, but so far have been unsuccessful? Below is the HTML snippet: <span class="pad-truck-number-position"><?php echo $_SESSION['truckId']; ?> ...

How to save the value of `this.$route.params.id` in a Vue.js data property?

I am currently working with Vue.js 3 and have a sample code for routing and passing parameters. Below is the Home.vue page: <template>   <div class="home">     <h1>       All Destinations     </h1>     < ...

Ensuring data validity in Angular 2 before enabling a checkbox

In my form, there is a checkbox for admins to edit user accounts. Each user object includes a boolean value isAdmin. I am trying to prevent users from editing their own account while still allowing them to view the values. However, no matter what I try, I ...

Error message: The Bootstrap .dropdown() method failed because it encountered an "Uncaught TypeError: undefined is not a function"

I've encountered an issue that seems to be a bit different from what others have experienced. Despite trying various solutions, I still can't seem to fix it. I suspect it might have something to do with how I'm importing my plugins. The erro ...

fade out row upon successful deletion using ajax

My code includes an AJAX function to delete items by row. In my table, there is a column with the action to perform the deletion. Here is the AJAX function: //delete detail function deleteDetail(id_po_req_detail) { var tr = ...

Tips for utilizing Plunker or JSFiddle to execute Angular2 code

I've been attempting to practice coding programs in Angular 2 using plnkr and jsfiddle. However, every time I try to run them, I encounter issues such as 404 errors or exceptions when I check the developer tools. Can anyone advise on the correct metho ...

What is the best way to eliminate or sort out array elements by detecting duplicate substrings in an associative array using PHP?

I am looking to eliminate duplicate titles in my array of songs. For example, if I have Rihanna - Work Ft. Some other words and Rihanna - Work, I only want to keep one version of the song. How can I achieve this while still being able to search for Rihanna ...

What is preventing the X-Powered-By Header from being disabled even after implementing helmet security measures?

After incorporating Helmet into my Express application and configuring it in app.js with the following code: app.use(helmet()); const helmet = require('helmet'); Upon restarting the app, the X-Powered-by header is still enabled despite using app ...