Function problem accessing previous node data

Hi there,
I tried to write (with chatGPT help) a little function that parse previous node data.
This is an example data directly copied from n8n (3 items there but it should be more or less) :slight_smile: Preformatted text

[
  {
    "code": "CEP",
    "text": "Gate out empty",
    "portCode": "MXESE",
    "location": "Ensenada",
    "date": "2023-10-13T06:48:00Z"
  },
  {
    "code": "VAT",
    "text": "Vessel arrival",
    "portCode": "ECGYE",
    "location": "Guayaquil",
    "date": "2023-11-05T16:00:00Z"
  },
  {
    "code": "VAD",
    "text": "Vessel arrival",
    "portCode": "BRSSZ",
    "location": "Santos",
    "date": "2023-12-11T10:00:00Z"
  }
]

My JS code :

const data2 = $input.all();
console.log("coucou"+data2)


const pairs = [];

for (let i = 0; i < data2.length - 1; i++) {
    const pair = {
        firstPortCode: data2[i].portCode,
        secondPortCode: data2[i + 1].portCode
    };
    pairs.push(pair);
}

return(pairs);

But if i replace data2 : const data2 = $input.all();
By the raw data i copied from previous node its work perfect :

const data2 = [
    {
        "code": "CEP",
        "text": "Gate out empty",
        "portCode": "MXESE",
        "location": "Ensenada",
        "date": "2023-10-13T06:48:00Z"
    },
    {
        "code": "VAT",
        "text": "Vessel arrival",
        "portCode": "ECGYE",
        "location": "Guayaquil",
        "date": "2023-11-05T16:00:00Z"
    },
    {
        "code": "VAD",
        "text": "Vessel arrival",
        "portCode": "BRSSZ",
        "location": "Santos",
        "date": "2023-12-11T10:00:00Z"
    }
];

It feels like a format problem but i dont understand why,

Glad if someone can help :slight_smile:

PS : iā€™m using a function node because i dont see how to do the same thing with classic nodes

Hey @dubarseo,

You get the error because of the wrong usage of n8n-data. Every object that comes from a node has this basic structure:

{
   json: {
      att1: "att1",
      att2: "att2"
   }
}

In your case that means one object looks like this

{
  json: {
           "code": "CEP",
           "text": "Gate out empty",
           "portCode": "MXESE",
           "location": "Ensenada",
           "date": "2023-10-13T06:48:00Z"
  }
}

That means in your code you simply need to change the to lines of portCode to:

...
firstPortCode: data2[i].json.portCode,
secondPortCode: data2[i + 1].json.portCode
...

Cheers

4 Likes

Wow perfect :slight_smile:
Big thanks !

1 Like

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