And I’m trying to use the variables further on down the line with $item("x"), except i’m struggling with errors as javascript is looking for data at indexes which don’t exist. They sometimes do, but sometimes they don’t, depending on the starting JSON, which changes every time. For instance in my example above there’s no 3rd entry, so using
$item("2").$node["CivList"].json["civilization"]
You’d get:
[No data found for item-index: "2"]
I have tried using a nullish operator {{ $item("2").$node["CivList"].json["civilization"] ?? "I am undefined!" }}
to suppress the error, but unfortunately n8n doesn’t like it when using item
Does anybody have any ideas on what I can do instead?
@UnluckyForSome , it is not quite clear to me if the index 2 is constant in your use case. If it is, then you can check if it exists first. For example,
Here, if index 2 exist (more than 2 items in the list) you can safely reference that index. Otherwise the value will be null and no error accessing non-existent item.
See here, I want to be able to reference item 273 in a future node. Most of the time it doens’t exist (in this example there are only 2 records not 273)
So in this instance I want to return “does not exist…” but the code errors out instead of returning
P.S there must be a better way of referencing the JSON output of a node, I used $input.all(); here in my example but I need to be more specific taking this to my actual workflow.
To fix, your JS code in Code node should look like this
const items = $input.all().map(i => i.json);
civiliz = items[273] ? items[273] : {civilization: "does not exist but we still return me anyway!"};
return civiliz;