0

How can I extend / implement a toString for my custom parse object?

Say for example I have a Parse object that contains "name" and "distance" fields.

var NearBy = Parse.Object.extend("NearBy");
new Parse.Query(NearBy).first().then(function(nearby) {
    nearby.get("name") // = maxim
    nearby.get("distance") // = 3
})

I would like JSON.stringify(nearby) to output { "name" : "maxim", "distance" : 3" }, instead it dumps "[object Object]"

Can that be fixed ?

Maxim Veksler
  • 29,272
  • 38
  • 131
  • 151
  • 2
    Try `console.log(typeof nearby)` ? I suspect `nearby` is already a string. Try `console.log(nearby)` too. – Prashanth Chandra Aug 18 '15 at 11:41
  • `I would like JSON.stringify(nearby) to output` where in your code would you like the to be the case? – Jaromanda X Aug 18 '15 at 11:43
  • http://stackoverflow.com/questions/16493498/json-stringify-returns-object-object-instead-of-the-contents-of-the-object Something might've called `toString` on `nearby` – Prashanth Chandra Aug 18 '15 at 11:49
  • @PrashanthChandra you were right. Simply doing console.log(nearby) magically worked. Please post this as an answer? so that i can accept? – Maxim Veksler Aug 18 '15 at 15:12

2 Answers2

1

You need to use JSON.stringify(nearby)

Reason is very simple, Right now you have a json object, which is not converted into any string, it is just an object. So when you run, you see, as should:

[object object]

Since right now you have in hand two objects of type JSON, You need to stringify them, in order to see them as strings and not as literal objects.

Your code should look like:

var NearBy = Parse.Object.extend("NearBy");
new Parse.Query(NearBy).first().then(function(nearby) {
    nearby.get("name") // = maxim
    nearby.get("distance") // = 3
    JSON.stringify(nearby);
})

This way your are taking your json, and converting it from object to a string, so you could work with it's properties as string.

Barr J
  • 10,636
  • 1
  • 28
  • 46
  • This is not the case, attempting to convert to string and failing is exactly the essence of my question. Please consider re-reading and making editing suggestions to improve clarity. – Maxim Veksler Aug 18 '15 at 15:15
0

Try console.log(typeof nearby) and see what it is? I suspect nearby is already a string.
Thus console.log(nearby) should work.

JSON.stringify returns "[object Object]" instead of the contents of the object

Community
  • 1
  • 1
Prashanth Chandra
  • 2,672
  • 3
  • 24
  • 42