How to iterate a for loop on a json output

Describe the issue/error/question

I have some json output and I’m trying to iterate on “childNodeIds” to construct HTML code that I can pass to the API. Ideally I’d like to have a line of this for each ID in “childNodeIds” and so it should look like:

<figure class="image image_resized" style="width:36.64%;"><img src="api/images/Uu5tIBz3IJsc/image.png"></figure>
<figure class="image image_resized" style="width:36.64%;"><img src="api/images/HUfo5NJjcJ15/image.png"></figure>
<figure class="image image_resized" style="width:36.64%;"><img src="api/images/5VfNZZXLRp49/image.png"></figure>

This is what I tried which works in regular javascript but I am getting Error: Code doesn’t return an object [item0]

var items = [{"results[0].childNoteIds":"Uu5tIBz3IJsc"},{"results[0].childNoteIds":"HUfo5NJjcJ15"},{"results[0].childNoteIds":"5VfNZZXLRp49"},{"results[0].childNoteIds":"9p6ESoZf18fU"}];
var temp = ""
for (let i = 0; i < items.length; i++) { temp += '<figure class="image image_resized" style="width:100%;"><img src="api/images/' + items[i]["results[0].childNoteIds"] + '/image.png"></figure>' }

console.log(temp);
return temp

What is the error message (if any)?

I’m struggling to understand how to select the childNodeIds to use it in a for loop.

Please share the workflow

Share the output returned by the last node

Information on your n8n setup

  • n8n version:
  • Database you’re using (default: SQLite):
  • Running n8n with the execution process [own(default), main]:
  • Running n8n via [Docker, npm, n8n.cloud, desktop app]:

Solved. Not sure if there’s a better way of doing this but this was my solution:

1 Like

Hey @Zhao,

That looks good to me, The good thing with n8n is there are many ways to do something.

Yeah, thanks.

Two things made me take quite a while - firstly getting to grips with the n8n structure and managing json data (which I hadn’t worked with before) was difficult.

I also conflated the code node not running with my JS code being wrong - but this was not the case as I found out it was that the code node expected a certain type of output. I’ve been more used to Node-Red’s flow where I can store a variable in a message output and use that in a later node along the same flow and expected the same thing here.

I’m sure the next time I make something in n8n it won’t take quite as long.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.