Loop through JSON in dataLayer - javascript

I would like to get the summed value of all the arrays in the "products" object (price * quantity). The summed value should be returned in the return.
Do you have any ideas how to do that?
{
"event": "checkout",
"ecommerce": {
"checkout": {
"actionField": {
"step": 2,
"option": "Initiate checkout",
"action": "checkout"
},
"products": [
{
"id": "52",
"name": "Turystyczna kuchenka gazowa SMILE-KN-03/1K",
"price": 161.788618,
"brand": "",
"category": "kuchenki-elektryczne-i-gazowe",
"variant": "",
"quantity": "1"
},
{
"id": "36",
"name": "Kuchnia gazowa MPM-51-KGF-21",
"price": 641.463415,
"brand": "",
"category": "kuchnie-gazowe",
"variant": "",
"quantity": "1"
}
]
}
},
"gtm.uniqueEventId": 12
}

const g = {
event: 'checkout',
ecommerce: {
checkout: {
actionField: {
step: 2,
option: 'Initiate checkout',
action: 'checkout',
},
products: [
{
id: '52',
name: 'Turystyczna kuchenka gazowa SMILE-KN-03/1K',
price: 161.788618,
brand: '',
category: 'kuchenki-elektryczne-i-gazowe',
variant: '',
quantity: '1',
},
{
id: '36',
name: 'Kuchnia gazowa MPM-51-KGF-21',
price: 641.463415,
brand: '',
category: 'kuchnie-gazowe',
variant: '',
quantity: '1',
},
],
},
},
'gtm.uniqueEventId': 12,
};
const c = g.ecommerce.checkout.products.reduce((acc, curr) => {
acc += curr.price * curr.quantity;
return acc;
}, 0);
console.log(c)
guess you want something like this?

Related

How to filter from an object by iterating over it in js

I am trying to get the value of "type" from the object by iterating over it. The object looks like this.
{
"team": {
"table": [
{
"cityCode": 123,
"list": {
"players": [
{
"name": "peter",
"school": "x",
"awards": {
"type": "gold"
},
"year": 2019
}
]
}
},
{
"cityCode": 456,
"list": {
"players": [
{
"name": "Dave",
"school": "y",
"awards": {
"type": "silver"
},
"year": 2018
}
]
}
}
]
}
}
I am able to get the type values using this:
const table = team.table;
for (let i = 0; i < table.length; i++) {
const values = {
type: table[i].list.players
.filter((a) => a.awards != null)
.map((a) => a.awards.type)
.join(" "),
};
}
However, I want to use another filter on the "list" to filter non null lists. So how can I achieve that.
You want to check Check if 'list' key exists inside a team.table JSON object
you can check by
if(table[i].hasOwnProperty('list')){
}
code is
const table = team.table;
for (let i = 0; i < table.length; i++) {
if(table[i].hasOwnProperty('list')){
const values = {
type: table[i].list.players
.filter((a) => a.awards != null)
.map((a) => a.awards.type)
.join(" "),
};
}
}
1) You can get all type using flatMap and map as:
obj.team.table.flatMap((o) => o.list.players.map((o) => o.awards.type))
const obj = {
team: {
table: [
{
cityCode: 123,
list: {
players: [
{
name: "peter",
school: "x",
awards: {
type: "gold",
},
year: 2019,
},
],
},
},
{
cityCode: 456,
list: {
players: [
{
name: "Dave",
school: "y",
awards: {
type: "silver",
},
year: 2018,
},
],
},
},
],
},
};
const types = obj.team.table.flatMap((o) => o.list.players.map((o) => o.awards.type));
console.log(types);
2) Using forEach and destructuring as:
const obj = {
team: {
table: [
{
cityCode: 123,
list: {
players: [
{
name: "peter",
school: "x",
awards: {
type: "gold",
},
year: 2019,
},
],
},
},
{
cityCode: 456,
list: {
players: [
{
name: "Dave",
school: "y",
awards: {
type: "silver",
},
year: 2018,
},
],
},
},
],
},
};
const table = obj.team.table;
const types = [];
for (let i = 0; i < table.length; i++) {
const { list: { players } } = table[i]
players.forEach(({ awards: { type }}) => types.push(type))
}
console.log(types);
It will be cleaner to use forEach.
You will need 2 forEach due to your data structure.
But below code will:
check if awards is null
check if awards.type is null
const data = {
"team": {
"table": [
{
"cityCode": 123,
"list": {
"players": [
{
"name": "peter",
"school": "x",
"awards": {
"type": "gold"
},
"year": 2019
}
]
}
},
{
"cityCode": 456,
"list": {
"players": [
{
"name": "Dave",
"school": "y",
"awards": {
"type": "silver"
},
"year": 2018
},
{
"name": "Dave",
"school": "y",
"awards": {
"type": "gold"
},
"year": 2016
}
]
}
},
{
"cityCode": 444,
"list": {
"players": [
{
"name": "James",
"school": "y",
"awards": {
"type": null
},
"year": 2016
}
]
}
},
{
"cityCode": 555,
"list": {
"players": [
{
"name": "Name 101",
"school": "y",
"awards": {
"type": "platinum"
},
"year": 2016
},
{
"name": "Name 102",
"school": "y",
"awards": {
"type": null
},
"year": 2016
},
{
"name": "Name 103",
"school": "y",
"awards": null,
"year": 2016
},
]
}
}
]
}
}
// Expanded your data with more items
const data1 = data.team.table;
let types = []
data1.forEach((item, index) => {
item.list.players.forEach((player) => {
const awards = player.awards;
if (awards !== null && awards.type !== null) {
types = [...types, awards.type];
}
})
})
// Get the list of types
console.log(types);
// Get unique list of types
let unique_types = [...new Set(types)]
console.log(unique_types);

Sort nested JSON array of objects

I have an array of objects as below. I want to recursively sort this based on the key values
{
"settingsList": [
{
"category1": [
{
"categoryName": "DRIVER",
"description": "DRIVER",
"sequence": 1
},
{
"categoryName": "BALL",
"description": "BALL",
"sequence": 2
},
{
"categoryName": "SAMPLE",
"description": "SAMPLE",
"sequence": 3
},
{
"categoryName": "USER",
"description": "USER",
"sequence": 4
}
]
},
{
"category2": [
{
"paramName": "CPP",
"description": "CPP",
"sequence": 1
},
{
"paramName": "PP",
"description": "PP",
"sequence": 2
},
{
"paramName": "MP",
"description": "MP",
"sequence": 3
}
]
}
{
"source": {
"instanceName": "instance_1"
}
}
]
}
How can I efficiently sort recursively to display it sorted alphabetically on the key values.
Expected output:
{
"settingsList": [
{
"category": [
{
"categoryName": "BALL",
"description": "BALL",
"sequence": 2
},
{
"categoryName": "DRIVER",
"description": "DRIVER",
"sequence": 1
},
{
"categoryName": "SAMPLE",
"description": "SAMPLE",
"sequence": 3
},
{
"categoryName": "USER",
"description": "USER",
"sequence": 4
}
]
},
{
"category2": [
{
"paramName": "CPP",
"description": "CPP",
"sequence": 1
},
{
"paramName": "MP",
"description": "MP",
"sequence": 3
},
{
"paramName": "PP",
"description": "PP",
"sequence": 2
}
]
},
{
"source": {
"instanceName": "instance_1"
}
}
]
}
below is the sample code that was tried
var object = {
"settingsList": [
{
"category1": [
{
"categoryName": "DRIVER",
"description": "DRIVER",
"sequence": 1
},
{
"categoryName": "BALL",
"description": "BALL",
"sequence": 2
},
{
"categoryName": "SAMPLE",
"description": "SAMPLE",
"sequence": 3
},
{
"categoryName": "USER",
"description": "USER",
"sequence": 4
}
]
},
{
"category2": [
{
"paramName": "CPP",
"description": "CPP",
"sequence": 1
},
{
"paramName": "PP",
"description": "PP",
"sequence": 2
},
{
"paramName": "MP",
"description": "MP",
"sequence": 3
}
]
},
{
"source": {
"instanceName": "instance_1"
}
}
]
}
var keys = Object.keys(object);
var sortedKeys = keys.sort((key1, key2)=>{
key1 = key1.toLowerCase();
key2 = key2.toLowerCase();
if(key1 < key2) return -1;
if(key1 > key2) return 1;
return 0;
})
function sortData(object){
var newObject = {},
keys = Object.keys(object);
keys.sort(function(key1, key2){
key1 = key1.toLowerCase();
key2 = key2.toLowerCase();
if(key1 < key2) return -1;
if(key1 > key2) return 1;
return 0;
});
for(var index in keys){
var key = keys[index];
if(typeof object[key] == 'object' && !(object[key] instanceof Array)){
newObject[key] = sortData(object[key]);
} else {
newObject[key] = object[key];
}
}
return newObject;
}
var sortedData=sortData(object)
console.log(sortedData)
....................................................................................................................................................................................................................................................................
What you tried to achieved is called deep sort.
You can use deep-sort-object library as follow :
var sortobject = require('deep-sort-object');
var sortedData = sortobject(object);
console.log(sortedData);
Or if you don't want to use a library, you can use this gist as reference.
Here is an iterative solution using object-scan
// const objectScan = require('object-scan');
const myData = { settingsList: [{ category1: [{ categoryName: 'DRIVER', description: 'DRIVER', sequence: 1 }, { categoryName: 'BALL', description: 'BALL', sequence: 2 }, { categoryName: 'SAMPLE', description: 'SAMPLE', sequence: 3 }, { categoryName: 'USER', description: 'USER', sequence: 4 }] }, { category2: [{ paramName: 'CPP', description: 'CPP', sequence: 1 }, { paramName: 'PP', description: 'PP', sequence: 2 }, { paramName: 'MP', description: 'MP', sequence: 3 }] }, { source: { instanceName: 'instance_1' } }] };
const sort = (data) => {
const logic = {
'settingsList[*].category1': (value) => value.sort((a, b) => a.categoryName.localeCompare(b.categoryName)),
'settingsList[*].category2': (value) => value.sort((a, b) => a.paramName.localeCompare(b.paramName))
};
objectScan(Object.keys(logic), {
filterFn: ({ value, matchedBy }) => {
matchedBy.forEach((needle) => logic[needle](value));
}
})(data);
};
console.log(sort(myData));
// => undefined
console.log(myData);
// => { settingsList: [ { category1: [ { categoryName: 'BALL', description: 'BALL', sequence: 2 }, { categoryName: 'DRIVER', description: 'DRIVER', sequence: 1 }, { categoryName: 'SAMPLE', description: 'SAMPLE', sequence: 3 }, { categoryName: 'USER', description: 'USER', sequence: 4 } ] }, { category2: [ { paramName: 'CPP', description: 'CPP', sequence: 1 }, { paramName: 'MP', description: 'MP', sequence: 3 }, { paramName: 'PP', description: 'PP', sequence: 2 } ] }, { source: { instanceName: 'instance_1' } } ] }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#14.4.0"></script>
Disclaimer: I'm the author of object-scan

How to order an array of objects in array of categories in javascript?

I have the following array of objects
{
"nome": "jose",
"categoria": [
{ "id": "1" },
{ "id": "3" },
]
},
{
"nome": "maria",
"categoria": [
{ "id": "2" },
]
},
{
"nome": "pedro",
"categoria": [
{ "id": "1" },
]
}
I have to reorder in another array of categories. Something like this:
{
"id": "1",
"pessoas": [
{
"nome": "jose",
"categoria": [
{ "id": "1" },
{ "id": "3" },
]
},
{
"nome": "pedro",
"categoria": [
{ "id": "1" },
]
},
]
},
{
"id": "2",
"pessoas": [
{
"nome": "maria",
"categoria": [
{ "id": "2" }
]
},
]
},
I have try with the function reduce(), but I couldn't because it is not an object, but a array of objects (categoria)
const group = data.reduce((r, array) => {
r[array.categoria.id] = [...r[array.categoria.id] || [], array];
return r;
}, {});
Someone can help me please?
You could take an object for grouping by id. Inside of reduce, categoria is iterated as well for getting the needed id.
var data = [{ nome: "jose", categoria: [{ id: "1" }, { id: "3" }] }, { nome: "maria", categoria: [{ id: "2" }] }, { nome: "pedro", categoria: [{ id: "1" }] }],
result = Object.values(data.reduce((r, o) => {
o.categoria.forEach(({ id }) => {
if (!r[id]) r[id] = { id, pessoas: [] };
r[id].pessoas.push(o);
});
return r;
}, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Aggregate data from nested array

I need help with the aggregate framework.
I have a model (currencies field can contain more than one object):
const schema = new mongoose.Schema({
country: { type: String },
code: { type: String },
region: [{
name: { type: String },
path: { type: Array },
city: [{
name: { type: String },
path: { type: Array },
latitude: { type: String },
longitude: { type: String },
}],
}],
currencies: [{
code: { type: String },
name: { type: String },
symbol: { type: String },
}],
})
And I need to receive all currencies without duplicates.
Received data can view like this:
[
{ code: 'string', name: 'sting', symbol: 'string' },
{ code: 'string', name: 'sting', symbol: 'string' },
...
]
// or like this:
[
currencies: [
{ code: 'string', name: 'sting', symbol: 'string' },
{ code: 'string', name: 'sting', symbol: 'string' },
...
]
]
I try to create a query
Geo.aggregate([
{
$group: {
_id: null,
currencies: { $addToSet: '$currencies' },
},
},
])
but receive this data with duplicates and it has many nested arrays:
[
{
"_id": null,
"currencies": [
[
{
"_id": "5cd9486248989616a411fac5",
"code": "JPY",
"name": "Japanese yen",
"symbol": "¥"
}
],
[
{
"_id": "5cd9491a48989616a411fb47",
"code": "TRY",
"name": "Turkish lira",
"symbol": null
}
],
I try this query:
Geo.aggregate([
{
$addFields: {
code: '$currencies.code',
name: '$currencies.name',
symbol: '$currencies.symbol',
},
},
])
But I receive error "TypeError: item is not iterable".
I need little help )
Db data views like this:
{
"_id": {
"$oid": "5c3334a8871695568817eadf"
},
"country": "Singapore",
"code": "sg",
"region": [
{
"path": [
"Singapore"
],
"_id": {
"$oid": "5c3366c63d92ac6e531e05c0"
},
"city": [],
"name": "Central Singapore Community Development Council"
},
....
],
"__v": 0,
"currencies": [
{
"_id": {
"$oid": "5cd948ec48989616a411fb28"
},
"code": "BND",
"name": "Brunei dollar",
"symbol": "$"
},
{
"_id": {
"$oid": "5cd948ec48989616a411fb27"
},
"code": "SGD",
"name": "Singapore dollar",
"symbol": "$"
}
]
}
In aggregate pipeline first you need to unwind the currencies array and then group them by condition to get desired result.
Geo.aggregate([
{
$unwind: '$currencies'
},
{
$group: {
_id: null,
currencies: { $addToSet: '$currencies' },
},
},
])
For more information you can look into documentation here
db.temp.aggregate([
{$project : {currencies : 1}},
{$unwind: "$currencies"},
{
$addFields: {
currencyHash: {
$concat : ['$currencies.code', "--", "$currencies.name", "--", "$currencies.symbol"]
}
}
},
{
$group: {
_id: "$currencyHash",
currency : {
$first : "$currencies"
}
}
},
{
$project: {
code : "$currency.code",
name : "$currency.name",
symbol : "$currency.symbol"
}
},
{
$project: {
_id : 0,
currency : 0
}
}
]).pretty()

How to make recursively nested array in javascript?

Below is the json I have:
{
"name": "test",
"characteristics": [
{
"name": "A",
"description": "",
"comprisedOf": [
{
"name": "A1",
"description": "",
"comprisedOf": [
{
"name": "A1.1",
"description": "",
"value": "10"
},
{
"name": "A1.2",
"description": "",
"value": "5"
}
]
},
{
"name": "A2",
"description": "",
"value": "100"
},
{
"name": "A3",
"description": "",
"value": "20"
},
{
"name": "A4",
"description": "",
"value": "50"
}
]
},
{
"name": "B",
"description": "",
"value": "10"
}
]
}
Here I have 2 characteristics object of "test" - A and B.These 2 objects may or may not have "comprisedOf" array. For Eg A has"comprisedOf" array whereas B has not. These comprisedOf array further may or may not have comprisedof objects array.
Now i have to make an array out of this which should be like the given below array:-
[
{
"name": "test",
"children": [
{
"name": "A",
"children": [
{
"name":"A1",
"children:: [
{
"name": "A1.1"
},
{
"name": "A1.2"
}
]
},
{
"name": "A2"
},
{
"name": "A3"
},
{
"name": "A4"
}
]
},
{
"name": "B"
}
]
}
]
How this array can be formed recursively out of the first array?
Thanks so much!!
EDIT:- Here's what I have tried:-
var makeChildrenAll = function(dataChar){
dataChar.forEach(function(char){
if(char.comprisedOf) {
makeChildrenAll(char.comprisedOf);
}
childrenData.push({
name: char.name,
description: char.description,
children: childrenData
});
});
};
makeChildrenAll(dataChar);
In order to be recursive you want the function to return and be able to assign that return to current object
Something like
function mapItems(arr){
// return new array
return arr.reduce((a,c)=>{
var newObj={name:c.name};
if(Array.isArray(c.comprisedOf)){
// use returned array of recursive function to assign to `children` property
newObj.children = mapItems(c.comprisedOf)
}
return a.concat(newObj)
},[])
}
console.log(mapItems(data.characteristics))
.as-console-wrapper { max-height: 100%!important;}
<script>
var data ={
"name": "test",
"characteristics": [
{
"name": "A",
"description": "",
"comprisedOf": [
{
"name": "A1",
"description": "",
"comprisedOf": [
{
"name": "A1.1",
"description": "",
"value": "10"
},
{
"name": "A1.2",
"description": "",
"value": "5"
}
]
},
{
"name": "A2",
"description": "",
"value": "100"
},
{
"name": "A3",
"description": "",
"value": "20"
},
{
"name": "A4",
"description": "",
"value": "50"
}
]
},
{
"name": "B",
"description": "",
"value": "10"
}
]
}
</script>
You could take a different start array and use a destructuring for the wanted properties.
function mapItems(array) {
return array.map(({ name, comprisedOf }) =>
Object.assign({ name }, comprisedOf && { children: mapItems(comprisedOf) }));
}
var data = { name: "test", characteristics: [{ name: "A", description: "", comprisedOf: [{ name: "A1", description: "", comprisedOf: [{ name: "A1.1", description: "", value: "10" }, { name: "A1.2", description: "", value: "5" }] }, { name: "A2", description: "", value: "100" }, { name: "A3", description: "", value: "20" }, { name: "A4", description: "", value: "50" }] }, { name: "B", description: "", value: "10" }] };
console.log(mapItems([{ name: data.name, comprisedOf: data.characteristics }]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
ES5
function mapItems(array) {
return array.map(function (o) {
var r = { name: o.name };
if (o.comprisedOf) {
r.children = mapItems(o.comprisedOf);
}
return r;
});
}
var data = { name: "test", characteristics: [{ name: "A", description: "", comprisedOf: [{ name: "A1", description: "", comprisedOf: [{ name: "A1.1", description: "", value: "10" }, { name: "A1.2", description: "", value: "5" }] }, { name: "A2", description: "", value: "100" }, { name: "A3", description: "", value: "20" }, { name: "A4", description: "", value: "50" }] }, { name: "B", description: "", value: "10" }] };
console.log(mapItems([{ name: data.name, comprisedOf: data.characteristics }]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Categories

Resources