I have a datalayer purchase object with two products (but user can buy more products):
This is an array I have:
[
{
name: "Product1",
id: 5986,
price: 980,
brand: "brand1",
category: "Cable & Adapter",
quantity: 1,
dimension51: "",
dimension52: "In Stock",
metric11: 980,
variant: 5771
},
{
name: "Prooduct2",
id: 5987,
price: 980,
brand: "brand2",
category: "Cable & Adapter",
quantity: 1,
dimension51: "",
dimension52: "In Stock",
metric11: 980,
variant: 5770
}
]
I want to create a JS function that would concatenate from each product ProductID and VariantID and it will return a list of productid_variantid.
I would like to via js the following:
5986_5771, 5987_5770
I have already this JS but it is returning undefined in Google Tag Manager.
function f(){
var p = {{dataLayer.ecommerce.purchase.products}};
var result = [];
for(var i=0;i<p.length;i++){
result.push(p[i].id.concat('_',p[i].variant));
}
return result.join(',');
}
Function f can be replaced with the following:
ES6:
function f(){
var p = {{dataLayer.ecommerce.purchase.products}};
return p.map(({id, variant}) => `${id}_${variant}`).join(',');
}
ES5:
function f(){
var p = {{dataLayer.ecommerce.purchase.products}};
const results = [];
for (let i = 0; i < p.length; i++) {
const product = p[i];
const resultString = p[i].id + '_' + p[i].variant;
results.push(resultString);
}
return results.join(',');
}
(The {{dataLayer.ecommerce.purchase.products}} syntax in your example is not valid in JavaScript, however I trust that this line works for you)
You can simply achieve that by a single line of code by using Array.map() method.
Try this :
const products = [
{
name: "Product1",
id: 5986,
price: 980,
brand: "brand1",
category: "Cable & Adapter",
quantity: 1,
dimension51: "",
dimension52: "In Stock",
metric11: 980,
variant: 5771
},
{
name: "Prooduct2",
id: 5987,
price: 980,
brand: "brand2",
category: "Cable & Adapter",
quantity: 1,
dimension51: "",
dimension52: "In Stock",
metric11: 980,
variant: 5770
}
];
const res = products.map((obj) => `${obj.id}_${obj.variant}`);
console.log(res.join(', '));
Updated as per the author comment (With normal forEach loop) :
const products = [
{
name: "Product1",
id: 5986,
price: 980,
brand: "brand1",
category: "Cable & Adapter",
quantity: 1,
dimension51: "",
dimension52: "In Stock",
metric11: 980,
variant: 5771
},
{
name: "Prooduct2",
id: 5987,
price: 980,
brand: "brand2",
category: "Cable & Adapter",
quantity: 1,
dimension51: "",
dimension52: "In Stock",
metric11: 980,
variant: 5770
}
];
const res = [];
products.forEach(function(obj) {
res.push(`${obj.id}_${obj.variant}`);
});
console.log(res.join(', '));
Related
I have the below Javascript object.
{
1: {
trade_date: "2022-12-09T00:00:00",
settlement_date: null,
trade_type: "Buy",
quantity: 25,
security_id: "AAPL",
price: 125,
portfolio_name: " Goldman Sachs.",
counter_party: null,
trader: "trader1"
},
2: {
trade_date: "2022-12-09T00:00:00",
settlement_date: null,
trade_type: "Buy",
quantity: 25,
security_id: "AMZN",
price: 105,
portfolio_name: "JPM",
counter_party: null,
trader: "trader2"
}
}
I want this to convert to as below.
Basically, 1 is trade_id. So, I want to give that name and make it as a list.
[
{
trade_id: 1,
trade_date: '12/9/2022',
settlement_date: '1/1/0001',
trade_type: 'Buy',
quantity: '25',
security_id: 'AAPL',
price: '125',
portfolio_name: 'Goldman Sachs',
counter_party: null,
trader: 'trader1',
},
{
trade_id: 2,
trade_date: '12/9/2022',
settlement_date: '1/1/0001',
trade_type: 'Buy',
quantity: '25',
security_id: 'AMZN',
price: '125',
portfolio_name: 'JPM',
counter_party: null,
trader: 'trader2',
},
];
You can map over Object.entries.
let obj={1:{trade_date:"2022-12-09T00:00:00",settlement_date:null,trade_type:"Buy",quantity:25,security_id:"AAPL",price:125,portfolio_name:" Goldman Sachs.",counter_party:null,trader:"trader1"},2:{trade_date:"2022-12-09T00:00:00",settlement_date:null,trade_type:"Buy",quantity:25,security_id:"AMZN",price:105,portfolio_name:"JPM",counter_party:null,trader:"trader2"}};
let res = Object.entries(obj).map(([id, v]) => ({trade_id: +id, ...v}));
console.log(res);
This is probably a good use case for Array.reduce - Iterate over the keys in the object, which allows you access each sequential list element, modify its properties, and add them to a new array.
const data = {
1: {
trade_date: "2022-12-09T00:00:00",
settlement_date: null,
trade_type: "Buy",
quantity: 25,
security_id: "AAPL",
price: 125,
portfolio_name: " Goldman Sachs.",
counter_party: null,
trader: "trader1"
},
2: {
trade_date: "2022-12-09T00:00:00",
settlement_date: null,
trade_type: "Buy",
quantity: 25,
security_id: "AMZN",
price: 105,
portfolio_name: "JPM",
counter_party: null,
trader: "trader2"
}
}
const reducedData = Object.keys(data).reduce((aggregate, key) => {
const currentElement = data[key];
currentElement["trade_id"] = parseInt(key);
aggregate.push(currentElement);
return aggregate;
}, []);
console.log(reducedData);
You can use a traditional for in loop to handle this scenario.
Loop over the object using for in
Append the index as trade_id in the object
Push the final object into an empty array
let obj = {
1: {
trade_date: "2022-12-09T00:00:00",
settlement_date: null,
trade_type: "Buy",
quantity: 25,
security_id: "AAPL",
price: 125,
portfolio_name: " Goldman Sachs.",
counter_party: null,
trader: "trader1"
},
2: {
trade_date: "2022-12-09T00:00:00",
settlement_date: null,
trade_type: "Buy",
quantity: 25,
security_id: "AMZN",
price: 105,
portfolio_name: "JPM",
counter_party: null,
trader: "trader2"
}
}
let result = []
for (const i in obj) {
// Double Bitwise NOT Operator to convert string to number
obj[i].trade_id = ~~i;
result.push(obj[i]);
}
In the code below how do i output try again only when the entire code execution runs and customer's order is not found amongst the product order in the menuItem dictionary.
I want to output this only when customer input doesn't match any product code
let menuItem = {
item_1: {
name: "french burger",
price: 1000,
productCode: 101
},
item_2: {
name: "chicken sharwama",
price: 1500,
productCode: 102
},
item_3: {
name: "pizza",
price: 5000,
productCode: 103
},
item_4: {
name: "beef sharwama",
price: 1500,
productCode: 104
},
item_5: {
name: "smoothie (mix flavor)",
price: 1300,
productCode: 105
}
}
listMenuItem = () => {
for (let i in menuItem) {
console.log(`Order Code: ${menuItem[i].productCode} || ${menuItem[i].name}, ${menuItem[i].price} NGN \n`)
}
}
listMenuItem()
var order = prompt("Enter product code to make your order: ")
console.log(order)
let customerOrder = []
for (let i in menuItem) {
if (menuItem[i].productCode == order) {
customerOrder.push(menuItem[i])
console.log(customerOrder)
console.log(`${menuItem[i].name}, ${menuItem[i].price}`)
} else {
console.log("Product does not exist, try again")
}
}
Your structure makes it harder to use the array methods.
The result is more confusing that it would have been if you just had an object keyed on productCode
let menuItem = {
item_1: {
name: "french burger",
price: 1000,
productCode: 101
},
item_2: {
name: "chicken sharwama",
price: 1500,
productCode: 102
},
item_3: {
name: "pizza",
price: 5000,
productCode: 103
},
item_4: {
name: "beef sharwama",
price: 1500,
productCode: 104
},
item_5: {
name: "smoothie (mix flavor)",
price: 1300,
productCode: 105
}
}
listMenuItem = () => {
for (let i in menuItem) {
console.log(`Order Code: ${menuItem[i].productCode} || ${menuItem[i].name}, ${menuItem[i].price} NGN \n`)
}
}
listMenuItem()
var order = +prompt("Enter product code to make your order: "); // convert the string to number or make the productCode a string in the object
console.log(order)
let customerOrder = Object.entries(menuItem).find(([key,{productCode}]) => productCode === order);
console.log(customerOrder)
if (customerOrder) {
console.log(`I found ${customerOrder[1].name}, ${customerOrder[1].price}`)
}
else {
console.log("Product does not exist, try again")
}
I have books data. I'd like to return the books if they match the author's id. When I try to filter out data that does not match my 'author's' id. However, it always returns all book data.
const author = "AUTHOR#e9bb9d29-7f20-4fce-892c-6a155dbee42c";
const Book = [
{
publishingYear: "2020",
rating: 5.2,
GSI1SK: "AUTHOR#a731ea70-f3f3-4811-9734-f22c0856385d",
genre: ["adventure", "drama", "scifi"],
GSI1PK: "AUTHOR",
page: 100,
publisher: "Afternoon pub",
SK: "BOOK#c4a58f20-4977-4db8-9723-0185f68cdf01",
price: "3.50",
PK: "BOOKS",
author: "Krishna",
title: "Me and mySelf"
},
{
publishingYear: "2020",
rating: 5.2,
GSI1SK: "AUTHOR#6b7c10ff-0e2c-46bd-9697-3b51730d8b29",
genre: ["adventure", "drama", "scifi"],
GSI1PK: "AUTHOR",
page: 100,
publisher: "Day pub",
SK: "BOOK#e4773a32-5451-42c6-a3f1-a6aa45176256",
price: "3.50",
PK: "BOOKS",
author: "John doe",
title: "Hello world"
},
{
publishingYear: "2020",
rating: 5.2,
GSI1SK: "AUTHOR#a731ea70-f3f3-4811-9734-f22c0856385d",
genre: ["adventure", "drama", "scifi"],
GSI1PK: "AUTHOR",
page: 100,
publisher: "Night Pub",
SK: "BOOK#fb56a876-41bc-49f9-9762-c48e90af3117",
price: "3.50",
PK: "BOOKS",
author: "Krishna",
title: "Amazing Race"
}
];
const Books = Book.filter((i) => {
console.log(i.GSI1SK);
i.GSI1SK === author;
return i;
});
console.log(Books);
You are using filter the wrong way, you should return true or false based on the condition you're matching,
const Books = Book.filter((i) => {
console.log(i.GSI1SK);
return i.GSI1SK === author;
});
And you can omit unnecessary lines. Try this.
const Books = Book.filter(i => i.GSI1SK === author)
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.
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)
Solves your thing but please do some research next time.
datalayer.products.map( (p, i) => ({[`product${i+1}`]: p.name }))
I'm beginner in JavaScript and I'm rendering a list that contains some products.
A product contains several sizes and each size has its price:
const data = [
{
id: "5286",
name: "Alyssa Ashley White Musk",
description: "Sensual but not overpowering",
categories: ["Fresh"],
sizes: [
{
name: "Sample",
price: 0,
},
{
name: "Normal",
price: 4000,
},
{
name: "Large",
price: 6500,
},
],
},
{
id: "6298",
name: "Euphoria",
description:
"Euphoria by Calvin Klein is a woody, oriental scent has notes of pomegranate, black violet, black orchid, and mahogany.",
categories: ["Floriental"],
sizes: [
{
name: "Normal",
price: 7100,
},
],
},
{
id: "9201",
name: "Emporio Armani",
description:
"Emporio Armani by Giorgio Armani bottles style and sophistication for women all over the world to enjoy.",
categories: ["Floriental"],
sizes: [
{
name: "Sample",
price: 0,
},
{
name: "Normal",
price: 2700,
},
],
},
];
export default data;
What I would like is, for example, sum all sizes of product 1 to get the total value. Sum all sizes of product 2 and getting the total value and so on. After obtaining the sum of all products. Sort the list in ascending ones.
I tried using the reducer function. But as inside each product it contains an array with the respective sizes and prices. I didn't know how to do it.
I put my code into codesandbox
Thank you in advance
It will be good to add totalSize key (which contains the sum of item sizes) on each item using Array.map and sort that using Array.sort.
const data = [
{
id: "5286",
name: "Alyssa Ashley White Musk",
description: "Sensual but not overpowering",
categories: ["Fresh"],
sizes: [
{
name: "Sample",
price: 0,
},
{
name: "Normal",
price: 4000,
},
{
name: "Large",
price: 6500,
},
],
},
{
id: "6298",
name: "Euphoria",
description:
"Euphoria by Calvin Klein is a woody, oriental scent has notes of pomegranate, black violet, black orchid, and mahogany.",
categories: ["Floriental"],
sizes: [
{
name: "Normal",
price: 7100,
},
],
},
{
id: "9201",
name: "Emporio Armani",
description:
"Emporio Armani by Giorgio Armani bottles style and sophistication for women all over the world to enjoy.",
categories: ["Floriental"],
sizes: [
{
name: "Sample",
price: 0,
},
{
name: "Normal",
price: 2700,
},
],
},
];
const result = data.map((item) => ({
...item,
totalSize: item.sizes.reduce((sum, cur) => (sum + cur.price), 0)
})).sort((a, b) => a.totalSize - b.totalSize);
console.log(result);