Skip to content

Strange behavior in map #34

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Tacklebox opened this issue Jul 30, 2018 · 2 comments
Closed

Strange behavior in map #34

Tacklebox opened this issue Jul 30, 2018 · 2 comments

Comments

@Tacklebox
Copy link

I noticed some strange behavior when escaping objects in an array using map. Only the first object is escaped as I would expect and the rest are strings of the type?

For example,

const sqlstring = require('sqlstring')
[{ id:1, name:'alice' }, { id:2, name:'bob' }, { id:3, name:'charlie' }].map(sqlstring.escape)

produces:

[ '`id` = 1, `name` = \'alice\'',
  '\'[object Object]\'',
  '\'[object Object]\'' ]

Do you know why this is happening?

If this is not expected behavior in some way I can try to put together a PR after I complete my current project if you like.

@dougwilson
Copy link
Member

This is because if how you're calling sqlstring.escape. See, you're passing the reference directly as the argument to the Array.prototype.map method. This method will call the given function with multiple arguments, namely currentValue, index, array (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map).

The sqlstring.escape method takes more than one argument, specifically val, stringifyObjects, timeZone.

If you break down the three calls, you'll find this is what is happening in your code:

[
  sqlstring.escape({ id: 1, name: 'alice' }, 0, [{ id:1, name:'alice' }, { id:2, name:'bob' }, { id:3, name:'charlie' }]),
  sqlstring.escape({ id: 2, name: 'bob' }, 1, [{ id:1, name:'alice' }, { id:2, name:'bob' }, { id:3, name:'charlie' }]),
  sqlstring.escape({ id: 3, name: 'charlie' }, 2, [{ id:1, name:'alice' }, { id:2, name:'bob' }, { id:3, name:'charlie' }])
]

The first call is passing 0 for the stringifyObjects argument, so objects are not stringified. The second two calls are passing in a truthy value, resulting in objects being returned as their .toString() output.

@Tacklebox
Copy link
Author

Wow, thanks for the quick reply!
I will close this issue then.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

2 participants