Remove array objects that don't contain a specific key

I'm really new to Node-Red and would like to know how to remove array objects that don't contain a specific key. Below is the first object from my array, it contains the key called 'clearedTime' - can I delete / remove all array items that contain this key? I just need the objects that do not have this key.

Thank you.

===============================

08/07/2020, 20:15:36node: 74ee711e.1992emsg.payload : Object

object

alarms: array[195]

[0 … 9]

0: object

id: "00809705-0b71-4fa8-a934-b9041cfe6919"

deviceId: "acb8c96e-db30-4b72-bd06-ab8706b43efd"

label: "No motion fault detected"

message: "Motion fault detection cleared for sensor Racks - Front-MOTION at NBRK0750"

severity: "INFO"

activatedTime: "2020-07-08T07:35:28.271Z"

clearedTime: "2020-07-08T07:36:19.065Z"

===============================

Hi and welcome.

This isn't really a node-red question (more generic JavaScript) but you could do this...

Pass the message through a function node...

msg.payload = msg.payload.filter(function( obj ) {
    return !obj.clearedTime;
});
return msg;

Hi, thanks for your reply much appreciated!
I did try your function code suggestion but this generated an error:

08/07/2020, 21:29:27node: 74ee711e.1992emsg.payload : Object

{ alarms: array[195], offset: "14438742" }

08/07/2020, 21:29:27node: Lengthfunction : (error)

"TypeError: msg.payload.filter is not a function"

:thinking:

Hi I took a punt based on what you posted. Looking back, it's quite hard to tell what is where.

Please use the copy button on the debug sidebar (the button appears when you hover an item in the debug bar) for posting data.

Also, when you post code or JSON please post it between backticks
```
like this
```

Also, post a screenshot of your flow and the debug output before the function node so we can see what is going into the function.

Hi Steve-Mcl, thanks fro your reply, here is the screen shot of my flow with debug output:

Thanks also for your instructions on how to post :slight_smile:

I can't see what's inside the array items & therefore can't advise on how to filter.

Can you expand one element of the array fully and screen shot (snip/copy/paste) just that part & I'll see if I can't help you get this sorted.

Here you go - thanks!

There are 195 objects in the array, most of them contain the key called 'clearedTime', it's these I want to remove so I only see the ones without this key in the object - hope I'm explaining this well enough for you?

Better :+1:

Try this...

msg.payload.alarms = msg.payload.alarms.filter(function( obj ) {
    return !obj.clearedTime;
});
return msg;

PERFECT !!! Thank you so much Steve-Mcl, great help!

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