Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
returns an array of objects that contains the product names

I am working on a javascript snippet for Google tag manager where i have to display the output like below.

[{"product1":"Protein Corn Muffin"},{"product2":"Salted Caramel Super Smoothie"},{"product3":"Pop Corn"},{"product4":"Fruit Pops!"}]

Attached datalayer.

dataLayer = {
  products: [
    {
      name: "Protein Corn Muffin",
      id: "SHOP - US - 6032011P",
      price: "5.95",
      quantity: 1,
    },
    {
      name: "Salted Caramel Super Smoothie",
      id: "SHOP - US - 6021050P",
      price: "7.95",
      quantity: 3,
    },
    {
      name: "Pop Corn",
      id: "SHOP - US - 4117050P",
      price: "8.95",
      quantity: 2,
    },
    {
      name: "Fruit Pops!",
      id: "SHOP - US - 41441109P",
      price: "9.99",
      quantity: 1,
    },
  ],
};
Can anyone guide me.
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Solves your thing but please do some research next time.

datalayer.products.map( (p, i) => ({[`product${i+1}`]: p.name }))

about 4 years ago · Juan Pablo Isaza Report

0

Another traditional solution:

var prods=[];
for(var i=0;i<dataLayer.products.length;i++){
   prods.push({['product'+(i+1)]: dataLayer.products[i].name});
}

Working Code

var dataLayer = {
  products: [{
      name: "Protein Corn Muffin",
      id: "SHOP - US - 6032011P",
      price: "5.95",
      quantity: 1,
    },
    {
      name: "Salted Caramel Super Smoothie",
      id: "SHOP - US - 6021050P",
      price: "7.95",
      quantity: 3,
    },
    {
      name: "Pop Corn",
      id: "SHOP - US - 4117050P",
      price: "8.95",
      quantity: 2,
    },
    {
      name: "Fruit Pops!",
      id: "SHOP - US - 41441109P",
      price: "9.99",
      quantity: 1,
    },
  ],
};


var prods = [];
for (var i = 0; i < dataLayer.products.length; i++) {
  prods.push({
    ['product' + (i + 1)]: dataLayer.products[i].name
  });
}

console.log(prods)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!