0

I have an array of strings, and a productId that is a type of object

productIds = [ '61b8b4a7ebffe000ec619219', '61c08d910579b11c103ba3b5' ];

productId = 61b8b4a7ebffe000ec619219;

The productId is a value from MongoDB which the field is type Object.Schema.ObjectId

Now, I want to check if productId is in productIds. Hence, I need to convert/parse productId to string.

Why is it that the code below results in true

productIds.includes(String(productId))
productIds[0] === String(productId)

While the code below results in false

productIds.includes(JSON.stringify(productId))
productIds[0] === JSON.stringify(productId)

Here is also the output of me testing each type

[ '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)
3
  • 1
    productId = 61b8b4a7ebffe000ec619219 is invalid javascript. If productId is a string, then JSON.stringify() adds additional quotes around the the string. Commented Jul 19, 2022 at 8:20
  • 1
    Did you log the result of JSON.stringify? (it explicitly wraps the string in double quotes). But the point is productId (despite your incorrect typing of it here) is probably a string already. Commented Jul 19, 2022 at 8:20
  • Sorry for that confusion, anyway the productId is just a value from a specific property of an object returned by mongoose { ..., orderedProducts: [..., { _product: ObjectId("61b8b4a7ebffe000ec619219") }] Commented Jul 19, 2022 at 8:28

1 Answer 1

2

productId = 61b8b4a7ebffe000ec619219;

That's a syntax error.

But leaving that aside:

String converts the value you pass to it into a string.

JSON.stringify converts the value you pass to it into string containing a JSON representation of that value.

In JSON, strings are delimited with ".

const data = "foo";

const string = String(data);
const json = JSON.stringify(data);

console.log(string);
console.log(json);

The differences with other data types become more pronounced:

const data = { "an": "object" };

const string = String(data);
const json = JSON.stringify(data);

console.log(string);
console.log(json);

Sign up to request clarification or add additional context in comments.

1 Comment

I understand, I will keep this in mind. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.