Ionic 2 and JSON Data Addition - javascript

I am working with Ionic 2 Storage to persist form data. I save the data like this:
this.storage.set(key, JSON.stringify(formData));
And I retrieve and attempt to update the data like this:
this.getReport(key).then((report) => {
var objReport = JSON.parse(report);
objReport.push(data); //this is the problem
this.storage.set(pk, JSON.stringify(objReport));
});
getReport is just this:
getReport(key) {
return this.storage.get(key);
}
So I know that .push is for arrays and not objects, but I don't think its efficient to do all this conversions because I am dealing with large objects.
My question is: what is the most efficient way to retrieve json from storage and append to it? It makes no sense to me that .parse returns an object if objects do not have a push method like arrays.
Here is the error:
Runtime Error Uncaught (in promise): TypeError: Cannot read property
'push' of undefined TypeError: Cannot read property 'push' of
undefined

what this error means is that, there are no records for that key at this moment.
So, you would have to do a check like this :
this.getReport(key).then((report) => {
var objReport = [];//initialise empty Array
if(report){ //if there is a record in that key location
objReport = JSON.parse(report); //parse the record & overwrite objReport
}
objReport.push(data); //Now this push will happen regardless of report or not
this.storage.set(pk, JSON.stringify(objReport));
});

Related

Possible memory leak in apps script array?

I'm building a Google Docs add on that pulls data from Jira.
The response object (issueMeta in the code below) is a JSON nested array with > 500,000 lines in it. The response object exists. I filter thru it to find an object with type.name === "Epic", which I've verified exists in the response data.
However on the last line I'm getting "TypeError: Cannot read property 'fields' of undefined", so it sounds like epicFields is not being set in the filter function.
I'm wondering if its a memory leak issue. Any ideas?
const issueMeta = getIssueMeta();
let epicFields = issueMeta.filter(function (type) {
return type.name === "Epic"
});
epicFields = epicFields[0].fields;

JavaScript toLowerCase() method returns an error in my react app

I am trying to convert all characters in a search field to lower case in my react app using the toLowerCase() method but gives the error typeError: Cannot read property 'toLowerCase' of undefined.
onSearchChange = (event) => {
const filteredRobots = this.state.robots.filter(robot => {
return robots.name.toLowerCase().includes(this.state.searchfield.toLowerCase());
})
You aren't including enough information to solve the issue, but here's my best guess:
Your robots.name.toLowerCase() should be robot.name.toLowerCase() instead (note the missing s on robot).
You're attempting to read the name property off the array you're filtering on rather than the current element that's being operated on.
My recommendation for when you run across errors like this in the future is to check your error log for something like this:
Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
at <myFunction>:1:27
This would read as TypeError in "myFunction" function at line 1, column (character) 27. You'd then be able to pinpoint exactly where your error is coming from. If you're still stuck, it's useful info to post along with your problem.
const filteredRobots = this.state.robots.filter(robot => {
return robot.name.toLowerCase().includes(this.state.searchfield.toLowerCase());
})
I think this is just typo.
Replace 'robots' with 'robot'

stringify object array to JSON Selectively

I have an Object array named users.
The object format in this array looks like this:
var userExample = {pub:{name:'John', id:'100'}, priv:{location:'NYC', phone:'000000'}};
As a restful service, clients may request information of all users.
And obviously I just want to send public information to them.
So I want to serialize my data selectively by keys(priv key will be ignored)
Here is my code snippet:
var users = [];
function censor(key, value) {
if (key == priv) {
return undefined;
}
return value;
}
app.get('/listUsers', function(req, res){
res.end(JSON.stringify(users, censor));
});
When I run these code, an error occurred:
ReferenceError: priv is not defined
I'm a Javascript beginner, please help.
Change priv to "priv".
But your approach is dangerous. In similar conditions I usually create a new object to export and I explicitly copy the properties which should be exported, this way there's no risk of leak on future data structure changes. A white list is always more future proof than a black list.
Newer versions of JSON.stringify() have a replacer array
E.g.
```
JSON.stringify(foo, ['week', 'month']);
// '{"week":45,"month":7}', only keep "week" and "month" properties
```
Try with:
if (key == "priv")
This should work.

Trying to access JSON object's array's children: Uncaught TypeError: Cannot read property 'length' of undefined

I am trying to get the Description array from a JSON object, loop it, and return it to the user.
I have JSON code in a format sort of like this:
[
{
"FoodNumber":"4567421",
"FoodName":"Banana",
"FoodCode":"110",
"DocumentDate":"19991223",
"ArrivalDate":"20020820",
"BogusField":"1241231",
"WhereFound":"In the jungle, man",
"DateEaten":"I dunno, every day?",
"Description":
[
"A vicious predator, the ravenous Banana stalks the jungles forcing monkeys to eat it",
"Monkeys think it's food, but it's really a parasite"
]
}
]
This is inside of ajax success: function (z). I parse it using var json = $.parseJSON(z.d);, and that allows me to access each individual data type, except Description. I need to be able to loop through that text array. I am currently using this jQuery code, and it works for all except Description:
var json = $.parseJSON(z.d);
$.each(json[0], function (i, obj) {
// obj.FoodName gives us the FoodName string, etc.
// ... lots of irrelevant code here
$.each(obj.Description, function (j, t) {
console.log(t);
});
// ... more code here.
});
When I use that looping code for the Description array, I get this error: Uncaught TypeError: Cannot read property 'length' of undefined.
What am I doing wrong? Any help would be appreciated.
Thanks!

cannot read property 'push' of null

I have a page which works on my localhost.. when I put t on a remote server, it gave an error. the code which returns the error is
var $app_list = localStorage.getItem('LsAppList');
var AppListJson = JSON.parse($app_list);
AppListJson.push({
"extapp_id": appdetail.get("addAppId"),
"desc": appdetail.get("addAppName"),
"device_no": appdetail.get("devicenoValue"),
"validation_key": appdetail.get("activationkeyValue")
});
the console log is
Uncaught TypeError: Cannot read property 'push' of null
addToJson EncigoHome.js:126
n.extend.trigger kendo.mobile.min.js:9
s.extend._release kendo.mobile.min.js:15
i._userEvents.o.UserEvents.tap kendo.mobile.min.js:15
n.extend.trigger kendo.mobile.min.js:9
l.extend.notify kendo.mobile.min.js:13
u.extend._trigger kendo.mobile.min.js:13
u.extend.end kendo.mobile.min.js:13
l.extend._eachTouch kendo.mobile.min.js:13
l.extend._end kendo.mobile.min.js:13
arguments.length.t.(anonymous function) kendo.mobile.min.js:10
b.event.dispatch jquery-1.9.1.js:9593
v.handle
localStorage is per domain (more specifically same origin). The localStorage associated with the remote domain does not have access to the values stored in the localStorage associated with your localhost.
You should check to see if there is a stored value and fallback to a default one or treat the error:
var $app_list = localStorage.getItem('LsAppList');
var AppListJson = $app_list != null ? JSON.parse($app_list) : [];
//...
More verbose:
var $app_list = localStorage.getItem('LsAppList'),
AppListJson;
if ($app_list != null) {
AppListJson = JSON.parse($app_list);
} else {
// treat no LsAppList stored case
// you could show a message or set it to a default value
AppListJson = [];
}
This "no previously stored data" scenario will happen whenever the user clears his browser data or switches browsers/devices as well, so it must be treated properly.
The root cause of the error, as you've probably figured out already, is that localStorage.getItem(key) returns null when no value is stored for the given key in the current domain. Then JSON.parse(null) === null and null.push() throws.
Just as a nitpick, I'd suggest reviewing your variables naming:
Don't use PascalCase naming for non-constructors.
Don't mix camelCase with underline naming conventions.
Recommended read: Idiomatic.js naming.
And also, AppListJson is not JSON, it is a native array. JSON can only exist in string context, that is, your $app_list is JSON. More in-depth explanation about JSON/not JSON: There's no such thing as a "JSON Object"
The .push() method can only be used on arrays.
It seems that you don't have the item stored in localStorage, which is why it is returning null

Categories