Change node > Delete from array (JSON)

Hey Guys,

New to Node-Red so sorry if this is basic. I have a simple flow, that fetches from an API and the result is a JSON object which is summarised below.

{ "results": [ 
    {"url": "https://myurl", "id": 1}, 
    {"url": "https://myurl", "id": 2}, 
    {"url": "https://myurl", "id": 3} ],
"next_page": "",
"count": 3
}

Reading through: https://nodered.org/docs/user-guide/messages it says that the easiest method of working with this object is to use "Change" as I want to drop "url" from each entry in the array. It is worth noting that the number of objects, is much higher than just 3, and there are more fields than just url to drop.

If i set "change" to "delete msg.payload.results[0].url" it drops it from the first result obviously, but cant find a way to make it do it for all of them.

Thanks in advance

You can use a jsonata expression
payload.results.url

Is this still using the Change node? As when I use the above it doesn't work.
As per the screenshot, url is still there.

Sometimes a function is easier...

msg.payload.results.forEach(function(v){ delete v.url });
return msg;
1 Like

Definitely easier when you know the language. Time to start learning Javascript

You are right, I failed to realise that there is no jsonata available for the delete option :grimacing:

In the change node you can use this to delete the url
payload ~> | results | {} , ['url']|
see https://docs.jsonata.org/control-operators#transform- and thank @shrickus :star_struck: for pointing me to that feature of jsonata

1 Like

So I started with @ukmoose's response worked perfect.
I actually changed it up instead and after some leaning went with a different approach, and that was to choose which values to keep rather than which ones to delete using map.

msg.payload.results = msg.payload.results.map(
    i => ({
        id: i.id,
        subject: i.subject.substring(0,99),
        status: i.status.substring(0,9),
        created_at: i.created_at,
        description: i.description.substring(0,99)
    })
)

return msg;

This cleans it up perfectly. Different from what I originally asked, but actually works better for my use case.

2 Likes

Another perfectly valid way to go, especially when you don't know what other fields may be present...

FWIW, the analogous way to build an array of pared-down objects using JSONata would be:

    payload.results[].{
        "id": id,
        "subject": subject.$substring(0,99),
        "status": status.$substring(0,9),
        "created_at": created_at,
        "description": description.substring(0,99)
    }