Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

custom array-like object looks like true array

I have custom array-like object, with all the array methods, which acts as an array, but Object.prototype.toString.call(myArrayLikeObj) returns [object Object] not [object Array]

How to prepare my object to return [object Array]?

Can I see somewhere Object.toString source code?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Symbol.toStringTag is the well-known name of the "tag" you want:

YourCustomArrayPrototype[Symbol.toStringTag] = () => 'Array'; // Sure, why not?

That said, if you extend Array you will get this for free:

class MyCustomArray extends Array {}

console.log(
  Object.prototype.toString.call(new MyCustomArray(3))
); // Logs [object Array]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading