Maxim Veksler
Maxim Veksler

Reputation: 30182

JSON.stringify of Parse.Object.extend returns "[object Object]"

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 ?

Upvotes: 0

Views: 559

Answers (2)

Prashanth Chandra
Prashanth Chandra

Reputation: 2692

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

Upvotes: 0

Barr J
Barr J

Reputation: 10929

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.

Upvotes: 1

Related Questions