Send an array of objects without specific fields

I am sending a response via AJAX that is an array of objects.

res.json(board.threads);

.threads is an array of objects that looks like:

[ 
	{ 
		_id: 5d89d85cf08c8c47b0f83230 
		created_on: 2019-08-26T17:24:36.496Z,
		replies: [ [Object] ],
		text: 'This is the first thread',
		delete_password: '123',
		reported: false,
		replycount: 1
	},
	{ 
		_id: 5d89d85cf08c8c47b0f83231 
		created_on: 2019-08-26T17:24:36.496Z,
		replies: [ [Object] ],
		text: 'This is the second thread',
		delete_password: '456',
		reported: false,
		replycount: 1
	},  
]

How do I send back the threads data array WITHOUT the ‘delete_password’ field?
Do I have to build up the response instead?

You can use .map on the array to remove the delete_password field.

threads = threads.map(obj => {
  delete obj.delete_password;
  return obj;
});

Or you can set your query to exclude that field. If you’re using Mongoose:

Board.find({}, { delete_password: 0 })
1 Like

You can map over the array of objects and use the delete syntax for the given field. Or destructure it and reassign detele password to null.

1 Like

Of course…!!! :roll_eyes:

using map() on the array would be a solution… why didn’t I think of this! :unamused:

I know this, I just never think of it! So frustrating.

Just a quick follow up…
I could not get this method to work:

Board.find({}, { delete_password: 0 })

so I used this:

Board.findOne({ board_title: boardTitle}).select("-delete_password")