I am working in Google Tag Manager on an ecomm site.
On the product pages I need to know the number of products that are in stock.
The dataLayer has sizes nested under each color option. Each size has a value showing if the size is in stock ("available": "false" or "true").
The code I am providing is what shows in the dataLayer. In this example, 3 of the 4 sizes are in stock, so I looking for the JS to run that will count the number of ""available": "true" - in this case the answer would be 3.
I am hoping for a solution that can be used in a variable in Google Tag Manager.
{
"product": {
"variants": [
{
"colorID": "03",
"colorName": "MEDIUM DENIM",
"sizes": [
{
"sizeID": "10",
"sizeName": "33",
"available": "false",
"price": "24.0"
},
{
"sizeID": "1",
"sizeName": "24",
"available": "true",
"price": "24.0"
}
]
},
{
"colorID": "06",
"colorName": "LIGHT DENIM",
"sizes": [
{
"sizeID": "1",
"sizeName": "24",
"available": "true",
"price": "24.0"
},
{
"sizeID": "2",
"sizeName": "25",
"available": "true",
"price": "24.0"
}
]
}
]
}
}
If I understand correctly what result is expected
const data = {"product": {"variants": [
{"colorID": "03","colorName": "MEDIUM DENIM","sizes": [
{"sizeID": "10","sizeName": "33","available": "false","price": "24.0"},
{"sizeID": "1","sizeName": "24","available": "true","price": "24.0"}]},
{"colorID": "06","colorName": "LIGHT DENIM","sizes": [
{"sizeID": "1","sizeName": "24","available": "true","price": "24.0"},
{"sizeID": "2","sizeName": "25","available": "true","price": "24.0"}]}]}};
const result = {
product: {
variants: data.product.variants.map((variant) => (
{
...variant,
sizes: variant.sizes.filter(({ available }) => available === "true"),
}
))
}
}
console.dir(result, {depth: null})
.as-console-wrapper{min-height: 100%!important; top: 0}
---- update ---
const data = {"product": {"variants": [
{"colorID": "03","colorName": "MEDIUM DENIM","sizes": [
{"sizeID": "10","sizeName": "33","available": "false","price": "24.0"},
{"sizeID": "1","sizeName": "24","available": "true","price": "24.0"}]},
{"colorID": "06","colorName": "LIGHT DENIM","sizes": [
{"sizeID": "1","sizeName": "24","available": "true","price": "24.0"},
{"sizeID": "2","sizeName": "25","available": "true","price": "24.0"}]}]}};
const result = data.product.variants
.flatMap((variant) => variant.sizes
.filter(({ available }) => available === "true")
).length;
console.dir(result, {depth: null})
.as-console-wrapper{min-height: 100%!important; top: 0}