Creating various arrays of JSON objects using JavaScript

I have a pre-existing array set up like this.

var dataLayer = [];
dataLayer = [{
'transactionProducts': [{
'sku': '96710381',
'name': 'QEH',
'category': 'GLD',
'price': '309.00',
'quantity': '3'
},
{
'sku': '96710382',
'name': 'RYP',
'category': 'FMT',
'price': '209.00',
'quantity': '3'
}]
}];

My goal now is to create another array with all the values from the existing one above. Here's how I've attempted it. However, only the first set of values gets transferred to the new array. The second set doesn't come through in the new array. Would appreciate some insights on how to resolve this issue!

var length = dataLayer[0]['transactionProducts'].length;
var len = dataLayer.length;
var gtmDataLayer = [];
var gtmDataLayer = [];
for (i=0;i<length;i++) {
var zsku = window.dataLayer[0]['transactionProducts'][i].sku;
var zsku = window.dataLayer[0]['transactionProducts'][i].sku;
var zname = window.dataLayer[0]['transactionProducts'][i].name;
var zcat = window.dataLayer[0]['transactionProducts'][i].category;
var zprice = window.dataLayer[0]['transactionProducts'][i].price;
var zquant = window.dataLayer[0]['transactionProducts'][i].quantity;
window.gtmDataLayer.push({
'transactionProducts': [{
'sku': zsku,
'name': zname,
'category': zcat,
'price': zprice,
'quantity': zquant
}]
});
}

Answer №1

Here's a solution for you.

var totalLength = dataLayer[0]["transactionProducts"].length;
var fullLength = dataLayer.length;
var updatedDataLayer = [{"transactionProducts":[]}];

for (i=0;i<totalLength;i++) {
    var itemSku = window.dataLayer[0]["transactionProducts"][i].sku;
    var itemName = window.dataLayer[0]["transactionProducts"][i].name;
    var itemCategory = window.dataLayer[0]["transactionProducts"][i].category;
    var itemPrice = window.dataLayer[0]["transactionProducts"][i].price;
    var itemQuantity = window.dataLayer[0]["transactionProducts"][i].quantity;

    updatedDataLayer[0]['transactionProducts'].push(
        {
        "sku": itemSku,
        "name": itemName,
        "category": itemCategory,
        "price": itemPrice,
        "quantity": itemQuantity
        }
    );
}

You might also consider automating the dynamic pushing of "transactionProducts" in the future.

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

Methods for attaching values to individual list items in Vue to switch images

Is there a way to toggle between two images by triggering a function on click event for different list items? Currently, all the list items display the same image because of a global value. How can I modify the code to toggle the images individually for ...

Generating an array from a string using intricate data types for visualization in Highcharts

Here is a text string that I am having trouble with: [[Date.UTC(2012,8, 1), 2],[Date.UTC(2012,9, 31), 3],[Date.UTC(2013,0, 31), 3]] When I manually paste the string, it works fine. However, I am unable to parse it using JSON.parse() due to the Date.UTC ...

What is causing my AJAX function to malfunction and throwing an exception for undefined data objects?

I am having trouble with my ajax query in my code. Even though it is returning the required data, it is not displaying properly within the HTML code. I have a common header and footer (PHP) for all other files. Despite my efforts to resolve this issue by s ...

Convert a TypeScript array of strings to a boolean array: a step-by-step guide

Upon receiving a list of objects from the front end as: item=["false","true"] I proceed to check a column within my records to identify values containing "true" or "false" using the following code: this.records.filter(x=> items.includes(x.column)) Unf ...

What is the best way to recycle a variable in TypeScript?

I am trying to utilize my variable children for various scenarios: var children = []; if (folderPath == '/') { var children = rootFolder; } else { var children = folder.childs; } However, I keep receiving the following error message ...

Unable to adjust the padding of the material UI Select component

I'm having trouble adjusting the padding of the Select component in order to align it with the size of my other text fields. Despite knowing that I need to make changes to nested components, I have yet to discover a viable solution. <div className ...

"Following successful POST login and session storage in MongoDB, the session is unable to be accessed due

When sending login data by POST with the credentials: 'include' option from client server 5500 to backend server 3000, I ensure that my session data is properly stored in MongoDB thanks to the use of 'connect-mongodb-session'. In the ba ...

What is the process for adjusting settings through selected options in a pop-up menu?

Here are the choices available: <form> <select id="poSelect" > <option selected disabled>Choose here</option> <option id="buyeroption" value="100101">I am a Buyer</option> ...

Cookies are failing to be saved upon reloading the page

I found this snippet of code $(document).ready(function () { var d = new Date(); var newMinutes = d.getTimezoneOffset(); var storedMinutes = getCookieValue("tzom"); if (newMinutes != storedMinutes) { setCookie("tzom", newMinutes) ...

onPropertyChange function exclusive to Internet Explorer

In Internet Explorer, the onPropertyChange event is functioning properly. I have utilized onPropertyChange to input text into one textbox and simultaneously display the same text in another textbox. Are there any alternate methods available to address this ...

The express js backend (mongodb) is returning {error:{ }}

I'm learning how to POST Data to a Mongo DB using Express.js. Recently, I picked up Express.js for backend server development and this is my app.js const express = require("express"); const mongoose = require("mongoose"); require("dotenv/config") con ...

What is the best way to handle invalid JSON when using json_decode()?

sample.php {"status": "yes"} {"status": "no"} output: yes , no I am encountering an issue with my website displaying a blank page(Using the code provided), can you offer any assistance in resolving it? <?php $da ...

Combining JSON data in Node.js with a custom structure is essential

Greetings! I'm currently working on a project that involves creating a JSON file using all the JSON files in a specific directory. My goal is to have this main JSON file automatically update whenever a new file is added to the directory. To achieve th ...

Following an AJAX request, jQuery.each() does not have access to the newly loaded CSS selectors

Note: While I value the opinions of others, I don't believe this issue is a duplicate based on the provided link. I have searched for a solution but have not found one that addresses my specific problem. Objective: Load HTML content to an element u ...

What methods are available for authentication to be shared among microservices?

I am managing two distinct Node.js services. Service X handles user authentication. Once a user successfully logs in, they are directed to Service Y (which is hosted on a subdomain of the domain where Service X resides). Authentication is done using JWT. ...

What is the best way to add an additional selected option after the page has been loaded?

I'm currently having trouble adding an extra option to a Chosen after the page has loaded completely. It works fine when I add values before the page loads, but once it's fully loaded, I can't seem to add values to the chosen component, as s ...

Angular2 recursive template navigation

Is it possible to create a recursive template in Angular 2 without using ng-include? It's puzzling why this feature seems to be missing in Angular 2... HTML: <div ng-app="app" ng-controller='AppCtrl'> <script type="text/ng-templat ...

Is it possible for me to add additional columns to the 2D array?

Can I create 2 cells in the first array and 4 cells in the second array using Java? Is this practice considered logical? Here's an example: public void stack(){ int a[][] = {{2,5234},{5,33,345,45}}; } ...

Searching JSON Data for Specific String Value Using JavaScript

I am looking for a straightforward approach to search my JSON string using JavaScript. Below is the PHP code that generates my JSON String: <?php $allnames = array(); $res = mysql_query("SELECT first,last FROM `tbl_names`"); while ($row = mysql_fetch_ ...

Display the information stored in an array onto the console using console.log in Angular with Typescript

.html file <div class="container" *ngFor="let info of (this.info || [])"> <h5 class="card-title" (click)="getInfo()">{{info.paragraph1}}</h5> </div> .ts file getInfo () { *****console.lo ...