Within my code, there exists an array of strings and a productId, which is an object of type ObjectId.
productIds = [ '61b8b4a7ebffe000ec619219', '61c08d910579b11c103ba3b5' ];
productId = 61b8b4a7ebffe000ec619219;
The productId is extracted from MongoDB and is of type Object.Schema.ObjectId.
My objective is to determine if productId
exists within productIds
. Therefore, I need to convert/parse the productId into a string.
I am puzzled by the fact that the following code results in true
productIds.includes(String(productId))
productIds[0] === String(productId)
Whereas, the code below gives false
productIds.includes(JSON.stringify(productId))
productIds[0] === JSON.stringify(productId)
Below are the outcomes of my testing different approaches
[ '61b8b4a7ebffe000ec619219', '61c08d910579b11c103ba3b5' ] | 61b8b4a7ebffe000ec619219 is type of object
productIds.includes(String(orderedProduct._product) true
productIds.includes(JSON.stringify(orderedProduct._product)) false
61b8b4a7ebffe000ec619219 is a typeof object 61b8b4a7ebffe000ec619219 is a typeof string
true using string String(61b8b4a7ebffe000ec619219)
false using stringify JSON.stringify(61b8b4a7ebffe000ec619219)