Hi there, I’m not super proficient with JavaScript, but am looking to use the JS column to convert a JSON object with a quantity property into multiple JSON objects, which I believe should work.
The following code works in JSFiddle, but I’m not returning any results in the Glide column (nor any errors):
function parseCart() {
let initialObject = p1;
let outputObjects = [];
for (let i = 0; i < initialObject.quantity; i++) {
outputObjects.push(JSON.stringify({
id: initialObject.id,
item: initialObject.item
}, null, 2));
}
return outputObjects.join(',');
}
return parseCart();
p1 is referencing a column with JSON that is formatted like so:
{
"id": "foo",
"item": "Item Title",
"quantity": 2
}
My desired output is to take the JSON object from p1 and split it into individual objects based on the quantity value:
{
"id": "foo",
"item": "Item Title"
},
{
"id": "foo",
"item": "Item Title"
}
Any assistance or pointing in the right direction would be so appreciated — thanks in advance!
You are trying to return an array. In Glide, you can only return strings. You need to add a .join() to the end of the array object. This should return all JSON objects as a comma delimited string.
@Jeff_Hager thanks so much for the quick reply! Apologies if I’m misunderstanding, but isn’t that what’s occurring with the line:
return outputObjects.join(',');
Or perhaps the .join() should be placed elsewhere instead?
Apologies. I glanced at your code quickly and missed the join. I thought it was just returning the full array.
If I were to guess again… 
I think it might be your input. It looks like the JSON string isn’t being turned into an object so initialObject is just text and doesn’t have a quantity attribute. I’ll play around a bit to see if that’s the case.
OK, just wanted to verify before I spit more lies.
All you should need to change is the initialObject definition. Change it to this:
let initialObject = JSON.parse(p1);
That worked beautifully — thank you very much for the help!
To clarify, it didn’t work initially because the JSON that you use as input is seen as a string, and not a JSON object, so you have to parse it first.