Loop array and append to a string variable - Event action advice needed

Hi all,

I am trying to take elements of an array and create a bit of formatted text so save in a multiline text field.

In my Code Studio Event Action I’ve got an array that looks similar to this:

[{
description": “Fridge”,
“OtherBulkyItems”: “”,
“ItemLocation”: "Outdoors ",
“ItemQuantity”: “1”
},
{
“Description”: “Freezer”,
“OtherBulkyItems”: “”,
“ItemLocation”: "Outdoors ",
“ItemQuantity”: “1”
}]

I’d like to be able to loop through this array and save a value to a multiline text field that looks like the below:

Fridge - Outdoors - No
Other item (if selected):
Location: Not provided
Quantity: 1
******************************************************
Freezer - Outdoors - No
Other item (if selected):
Location: Not provided
Quantity: 1
******************************************************

Any advice on how I can achieve this will be gratefully received.

Thank you

Adam.

const items = [

{ name: “Fridge”, location: “Outdoors”, otherItem: true, quantity: 1 },

{ name: “Freezer”, location: “Outdoors”, otherItem: false, quantity: 1 }

];

const output = items.map(item => {

const locationText = item.location && item.location.trim() !== “” ? item.location : “Not provided”;

return `${item.name} - ${locationText} - ${item.otherItem ? “Yes” : “No”}

Other item (if selected):

Location: ${locationText}

Quantity: ${item.quantity}

*******************************`;

}).join(“\n\n”);

console.log(output);

Thanks Ian, I seem to be getting this error if I use that code - TypeError: items.map is not a function.

Any ideas?

Ah right! Sorry, I did this outside of Create and it used different double quotes. Try the below, if copying this is still an issue manually change the quotes.

	const items = [{ name: "Fridge", location: "Outdoors", otherItem: false, quantity: 1 },
	{ name: "Freezer", 'location': "Outdoors", 'otherItem': true, 'quantity': 1 }
	];

	const output = items.map(item => {

		const locationText = item.location && item.location.trim() !== "" ? item.location : "Not provided";

		return `${item.name} - ${locationText} - ${item.otherItem ? 'Yes' : 'No'}
		Other item (if selected):
		Location: ${locationText}
		Quantity: ${item.quantity}
		*******************************`;
	}).join("\n\n");

Thank you Ian, that is perfect and is now looping the array and I’m able to take the output and save it to a field for later use.

1 Like