Inject new value in array

Hey there,
I’m really bad in using the code node, so I hope someone could help me here, I tried with the non-code nodes but I failed.
I have this json output from an HTTP get:

[
  {
    "data": {
      "id_number": 1,
      "items": [
        {
          "my_number": 18,
          "my_name": "Jhon"
        },
        {
          "my_number": 34,
          "my_name": "Jack"
        }
      ],
      "pagination": null
    },
    "error": false,
    "error_message": null,
    "error_code": null
  },
  {
    "data": {
      "id_number": 20,
      "items": [
        {
          "my_number": 23,
          "my_name": "Jenny"
        },
        {
          "my_number": 45,
          "my_name": "Clark"
        }
      ],
      "pagination": null
    },
    "error": false,
    "error_message": null,
    "error_code": null
  }
]

Want I want to achieve, is to have the corrispondent “id_number” field injected to each item in the array like below:

[
  {
    "data": {
      "items": [
        {
          "id_number": 1,
          "my_number": 18,
          "my_name": "Jhon"
        },
        {
          "id_number": 1,
          "my_number": 34,
          "my_name": "Jack"
        }
      ],
      "pagination": null
    },
    "error": false,
    "error_message": null,
    "error_code": null
  },
  {
    "data": {
      "items": [
        {
          "id_number": 20,
          "my_number": 23,
          "my_name": "Jenny"
        },
        {
          "id_number": 20,
          "my_number": 45,
          "my_name": "Clark"
        }
      ],
      "pagination": null
    },
    "error": false,
    "error_message": null,
    "error_code": null
  }
]

Thanks in advance!

me again, thanks to @RicardoE105 for his reply at How to add a key:value pair from the top level array to all sub-arrays I forked that script and playing around I got this working:

const _dataarr = []
for(let i=0; i<items.length; i++){

const { data, id_number} = items[i].json;
for (const dat of data) {
    _dataarr.push({
      number: dat.my_number,
      name: dat.my_name,
      id_number,
    })
}
}
return _dataarr;
2 Likes

@GBOL Nice! Can you please provide an example with your test data? I tried your code, but keep getting an ERROR: data is not iterable [line 5]

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