I have been working on a project that uses a object to maintain a conversation with the user. However if what has been asked by the user is not in this object. The user is prompted for what should the "AI" answer. The problem is that I can't save this object, so when the user closes the tab or reloads it everything that the "AI" has learned disappears. I've tried using localStorage.setItem('dictionary', JSON.stringify(dictionary)) (dictionary is the object) However it gave me "[object Object]". So i was wondering if there was anyway I could use cookies instead?
after you store your object you need to use it like this,
var dictonaryParsed = JSON.parse(localStorage.getItem('dictionary'));
this will fix your problem, this is because localStorage.setItem() will use the toString() method from the prototype chain, and you will get this [object Object].
This is because everything is converted to string before stored to the key,value pair database(localStorage).
With stringify method that you are using the object will be prepared for the JSON.parse() method if not used you will get something like this "{"a":10}", so you need to Parse your object before using it. If you try to parse not stringyfied object you will get error.
the localstorage you use has no problem,did you alert the object and you see the '[object Object]'?
Related
I'm working on a WebView app in React Native, and I need to handle the messages sent by website (using postMessage) using the onMessage callback. As per the docs -
window.postMessage accepts one argument, data, which will be available
on the event object, event.nativeEvent.data. data must be a string.
But the the string (event.nativeData.data) that I am getting in my onMessage() function is '[object Object]' which I know is the result of calling toString() method on an Object.
Is there any way to get back the JavaScript Object obj from the resulting String obtained using obj.toString() ?
I tried JSON.parse() but it only gives the error as shown in the attached image below.
Thanks !
Is there any way to get back the JavaScript Object obj from the resulting String obtained using obj.toString() ?
No. The data in the object simply does not appear in the string.
You can tell this just by looking at the string! There is nothing that either resembles the original data nor which looks like an encoded something.
If you want to preserve the data, then use JSON.stringify to convert it to a string instead of converting it with .toString().
I have an object req.user.stripe that has a value of an empty object {}.
I would like to use the lodash function isEmpty() to check if this object is empty or not. When I run console.log(_.isEmpty(req.user.stripe)), I get a return value of false. console.log(req.user.stripe) in fact returns an empty object {}.
Not sure what I am missing. I am open to using a different method aside from lodash. Essentially, I need to access properties within req.user.stripe, but only if req.user.stripe is not an empty object (otherwise I'll get an error saying that JS cannot read property x on undefined).
Clarification
In my mongoose schema, when a user is created, they are created with a stripe parameter, but it defaults to an empty object {}. Only when we actually talk to stripe does that fill up with data. I have a number of beta users in my system that were given accounts, but not through the same process as someone registering on the frontend. These users are now required to pay, but they have to keep their accounts. I need to detect if a user has stripe information or not, hence why I am checking if the stripe parameter in the req.user object is or is not an empty object.
For example, if I want to access that last 4 digits of a user's saved card, I can access it this way req.user.stripe.customer.sources.data[0].last4. However, when trying to access a user without stripe data, an error similar to Cannot read property 'sources' of undefined. I need to be able to handle conditions like this when the req.user.stripe object is empty.
Before accessing that property use an if statement:
if(req.user && req.user.stripe) { do_your_thing() }
There's three options here:
Your object isn't actually empty, it just appears empty on the console for some reason.
It's actually empty when you do the console.log, but not when you do _.isEmpty (As suggested by #Todd Chaffee in the comments; but I find this doubtful)
There's a bug in _.isEmpty. (I also find this one doubtful, but it's a possibility)
But, as others have said in the comments, I don't think _.isEmpty is what you want in the first place.
To take your example of req.user.stripe.customer.sources.data[0].last4: what if req.user.stripe isn't empty, but customer isn't defined, or it's empty, or it's defined but the sources.data array is undefined or empty, or etc? Sure, maybe all of those situations are completely impossible in the current code, but will they always be? _.isEmpty(req.user.stripe) is a fairly fragile test.
A safer alternative is _.get(req, "user.stripe.customer.sources.data[0].last4"), which will just return null if any of those intermediary properties are null.
...but frankly it smells of a larger structure issue that you're trying to get the last4 digits of a credit card without knowing whether or not you've even got a customer in the first place.
This is an old question, but using _.isNil(object) solved this problem for me, returns if object is null or empty.
I have some JavaScript code that needs to be able to access fields of an array of objects that is contained within my model. I currently have this:
var model = #Html.Raw(Json.Encode(Model));
for(var i = 0; i < model.testobject.length; i++) {
console.log(model.testobject[i]);
}
Which prints out the fields within each object of testobject. But say I have a field, ID, in my testobject class. How do I then access that? Doing this:
console.log(model.testobject[i].ID);
Does not work. Do I have to somehow encode that specific instance of testobject before accessing it's fields?
And yes, before anyone says it I know this should be contained within the controller. As it currently stands though, that's not possible for this project.
This is the general structure of what is printed out:
Object {field: value}
Edit:
I attempted to use JSON.stringify on my model.IdentifiApprovalConfigurations and it seems I got a little close to reaching my solution. This is what it looks like now:
console.log(JSON.stringify(model.testobject[i]).ID);
However, this prints out undefined.
Edit 2:
Oops, seems the ID field I'm trying to access isn't being populated before I send them to my view which is my own issue. JSON.stringify works though, and I understand why it wasn't working earlier.
Final edit:
JSON.parse(JSON.stringify(model.testobject[i])).Value
I had to stringify and then parse my JSON to access the value.
As I'm still starting out with web development, I forgot that I needed to convert my object into a JSON object. This:
JSON.parse(JSON.stringify(model.testobject[i])).Value
Is the final piece of code that allows me to stringify an object, parse the JSON and then access fields within that object.
I'm getting a result (the object) back from a mongoose query and want to replace/remove some keys, before I stringify the object and send it to the client.
When I console.log the object, everything is nice (all the keys are listed, nothing more). When I do a for..in on the object, hidden fields popup out of nowhere (and the keys of interest, don't). They make sense - they belong to mongoose - but I don't want them. Same thing happens, when using Object.keys or Object.getOwnPropertyNames on the Object - hidden fields popup, none useful.
So I wanted to inspect the element with util.inspect(obj,true,null,true) and log the result to console. The result on the console is the same, as if I'd console.logged the object directly without the inspection.
Now, two questions;
How do I correctly inspect an object, so that I actually get internal/hidden information about the object?
How can I iterate over the object and only get the fields? (yes, I am doing the hasOwnProperty check within the for..in loop)
//EDIT
OK, I got it. After some investigation, I realized, that the mongoose object proxies its properties and has a toJSON function, which explains why the console.logs were in the expected output structure. The solution is to use Mongoose own toObject method;
mongooseObj.toObject({ getters: true, virtuals: false })
This way, I can iterate over Object.getOwnPropertyNames and replace/remove keys I don't want the client to know about!
I'm going to guess that you're looking at the Document object returned by a mongoose query when you really just want to see the data. If my guess is correct, you'll probably want something like this:
Model.findOne({ name: 'john' }, function (err, doc) {
var data = doc.toObject();
// do whatever you need to with data
delete data.age;
delete data.weight;
data.isAwesome = true;
// now stringify the data and do something with it
callback(JSON.stringify(data));
});
Also if you want to access a certain field from a Document you can take a look at:
Document#get
// path
doc.get('age') // 47
// dynamic casting to a string
doc.get('age', String) // "47"
I am attempting to parse the incoming JSON from XBMC (Eden Beta v3), an example string from XBMC is as follows:
{"jsonrpc":"2.0","method":"Player.OnPlay","params":{"data":{"item":{"type":"movie"},"player":{"playerid":1,"speed":1},"title":""},"sender":"xbmc"}}
I am using json2.js from https://github.com/douglascrockford/JSON-js/blob/master/json2.js to give me the JSON.parse and JSON.stringify functions in my application.
I am using the parse function in my code like this
var temp = JSON.parse(data);
Which is working fine for the first two properties, "jsonrpc" and "method"... so I can access those like this
temp.method
returns "Player.OnPlay"
temp.jsonrpc
returns "2.0"
However, if you look at the string sent by XBMC, it also contains what they refer to as "extended parameters" or "params", I cannot seem to track down what the JSON parser is doing with the rest of the message, or how I can access them in similar ways as the first two properties. If I try
params = temp.params
or any other way of accessing the params property, I get an Undefined error as there is no such property in the JSON object... I hope this is clear enough for someone to take a stab at helping me out. Will provide any extra info needed...
Thanks
The value of params in the JSON data is an object, so you have to access the sub-properties of that.
temp.jsonrpc
temp.method
temp.params["data"]["item"]["type"]
temp.params["data"]["player"]["playerid"]
temp.params["data"]["player"]["speed"]
temp.params["data"]["item"]["title"]
temp.params["sender"]