i got error : Cannot read property 'push' of null - javascript

I tried like this reference, but it did not work anyway.
This is a new thing for me, and just started learning javascript.
var getTbl = localStorage.getItem("tableList");
var resultTable = [];
if (getTbl !== undefined && getTbl !== '') {
resultTable = JSON.parse(getTbl);
}
let newtableHTML = addTable;
resultTable.push({
table: newtableHTML
});
// save the new resultFolder array
localStorage.setItem("tableList", JSON.stringify(resultTable));
i try something like this, but no luck :
var resultTable = resultTable || [];
Sorry if I'm wrong in trying that way.

The line
resultTable = JSON.parse(getTbl);
replaces the contents of the resultTable variable with whatever JSON.parse returns. Apparently JSON.parse is not returning an array (or other kind of object with a push method, but arrays are the only built-in ones that do).
My guess is that it's returning null, because getItem returns null if the key doesn't exist in local storage, but you're not checking for that. So you're passing null into JSON.parse, it gets coerced to string ("null"), and then parsed as JSON, yielding...null.
Since you're storing an array (and arrays are never falsy), I'd probably do this:
var getTbl = localStorage.getItem("tableList");
var resultTable = getTbl ? JSON.parse(getTbl) : []; // <====
let newtableHTML = addTable;
resultTable.push({
table: newtableHTML
});
// save the new resultFolder array
localStorage.setItem("tableList", JSON.stringify(resultTable));
That tests if what getItem gave us was falsy and, if it is, uses [] instead.
But there are a dozen variations on this theme. For instance:
var resultTable = JSON.parse(localStorage.getItem("tableList") || "[]"); // <===
let newtableHTML = addTable;
resultTable.push({
table: newtableHTML
});
// save the new resultFolder array
localStorage.setItem("tableList", JSON.stringify(resultTable));

Change the way 'resultTable' is initialised to :
resultTable = new Array();
So that data can be pushed properly to resultTable.

Related

console gives a string isn't a function error

I'm creating a quiz and console shows a problem with split, that it's not a function, but it worked before. I've tried using toString method but it doesn't help, console says instead that can't read properties of null. If someone could help me, it would be appreciated.
let correctAnswer = document.getElementById("correct-answers");
document.querySelector(".check").onclick = function () {
/* Hide unneeded sections and showing scores */
quiz.classList.add("hidden");
correctAnswer.classList.remove("hidden");
/*Showing all previous scores */
const lastScore = localStorage.getItem("latestScore") || [];
const scoreDetail = lastScore.split(',');
scoreDetail.push(score);
localStorage.setItem("latestScore", scoreDetail);
let userScoreTemplate = `<h2>This Round's Score: ${score}</h2>`;
scoreDetail.map((items, index) => {
userScoreTemplate += `<h3>Score ${index}: ${items}</h3>`
});
let userScoreBoard = document.getElementById("user-score");
userScoreBoard.innerHTML = userScoreTemplate;
localStorage.getItem() will return a string.
You need adjust your code accordingly to default to a string in case the item is not defined:
const lastScore = localStorage.getItem("latestScore") || "";
In your code lastScore is an array, not a string, so the split method will not work on it. It works only on strings.You can use JSON.Parse like that. This will convert array data into javascript array.
const scoreDetail = JSON.parse(lastScore) || [];
scoreDetail.push(score);
And after that convert the array into a JSON string :
localStorage.setItem("latestScore", JSON.stringify(scoreDetail));
is latest score is a obj/array/string or what?
If it's an array/object then wrap localStorage.getItem in JSON.parse() so js can convert array data into js array
As per the error, You are trying to apply split on an array instead of a string.
Looks like, localStorage.getItem("latestScore") is undefined while you are trying to access it and it assigned an empty array to lastScore variable.
Hence, Instead of
const lastScore = localStorage.getItem("latestScore") || [];
Use
const lastScore = localStorage.getItem("latestScore") || "";

excel javascript API array handling

I'm working on an add-in for excel 2016 using the javascript API. I can successfully get the range into an array and get the values to show in console.log. I've also been able to get the values into a JSON array using JSON.stringify();
I need to manipulate the array to remove the empty values ("").
Can this be accomplished by using regular javascript array methods?
I'm thinking I can display the results back into a different worksheet using a similar approach like i did with var shWk
Here are some snippets of what I'm trying to do:
(function () {
"use strict";
// The initialize function must be run each time a new page is loaded
Office.initialize = function (reason) {
$(document).ready(function () {
app.initialize();
//document.getElementById("date").innerHTML = Date("MAR 30 2017");
$('#deleteTab').click(deleteTab);
$('#preview').click(preview);
$('#publish').click(publish);
});
};
function preview() {
Excel.run(function(ctx) {
//getting the colname from a date range in B2
var colName = ctx.workbook.worksheets.getItem('preview').getRange("B2");
colName.load('values');
return ctx.sync().then(function() {
//converting colname value to string for column name
var wkN = (colName.values).toString();
// displaying on the task pane
document.getElementById("tst").innerText = wkN;
// testing to confirm i got the correct colname
var shWk = ctx.workbook.worksheets.getItem('preview').getRange("B3");
shWk.values = colName.values;
//building the column connection by setting the table name located on a different worksheet
var tblName = 'PILOT_ZMRP1';
var tblWK = ctx.workbook.tables.getItem(tblName).columns.getItem(wkN);
//loading up tblWK
tblWK.load('values');
return ctx.sync().then(function(){
//this is where my question is:
var arry = tblWK.values;
for (var i=0; i < tblWK.length; i++){
if (tblWK.values !== ""){
arry.values[i][0]) = tblWK.values[i][0]
};
};
console.log(arry.length); //returns 185
console.log (arry.values);//returns undefined
tblWK.values = arry;
var tblWeek = tblWK.values;
console.log(tblWeek.length);//returns 185
console.log(tblWK.values);//returns [object Array] [Array[1],Array[2]
})
});
}).catch(function (error) {
console.log(error);
console.log("debug info: " + JSON.stringify(error.debugInfo));
});
}
What am I missing? Can you point me to some resources for javascript array handling in the specific context of office.js?
I want to thank everyone for the time spent looking at this question. This is my second question ever posted on Stack Overflow. I see that the question was not written as clear as it could've been. What i was trying to achieve was filtering out the values in a 1D array that had "". The data populating the array was from a column in a separate worksheet that had empty values (hence the "") and numeric values in it. the code below resolved my issue.
//using .filter()
var itm = tblWK.values;
function filt(itm){
return itm != "";
}
var arry = [];
var sht = [];
var j=0;
var s=0;
arry.values = tblWK.values.filter(filt);
//then to build the display range to show the values:
for (var i=0; i < itm.length-1; i++) {
if (tblWK.values[i][0]){
var arry; //tblWK.values.splice(i,0); -splice did not work, maybe my syntax was wrong?
console.log("this printed: "+tblWK.values[i][0]);
var cl = ('D'+i); //building the range for display
j++; //increasing the range
s=1;//setting the beignning range
var cll = cl.toString();//getRange() must be a string
console.log(cll);//testing the output
}
}
//using the variable from the for loop
var cl = ('D'+s+':D'+j);
var cll = cl.toString();
console.log(cll);//testing the build string
sht = ctx.workbook.worksheets.getItem('Preview').getRange(cll);
sht.values = arry.values; //displays on the preview tab
console.log (arry.values); //testing the output
The question was probably easier said by asking what vanilla javascript functions does office.js support. I found a lot help reading Building Office Add-ins using Office.js by Micheal Zlatkovsky and by reading the MDN documentation as well as the suggested answer posted here.
Regards,
J
I'm not sure what this check is trying to achieve: tblWK.values !== "". .values is a 2D array and won't ever be "".
For Excel, the value "" means that the cell is empty. In other words, if you want to clear a cell, you assign to "". null value assignment results in no-op.
You can just fetch the values form the array that contains null by using for each and can can push the null values into another array.

How to access Object within JSON?

Context
If I have the following JSON data:
{"response":"success","data":[{"id":"2"}]}
I'm trying to get the ID that is sent through, 2.
Attempts
I've tried the following:
var r = JSON.parse('{"response":"success","data":[{"id":"2"}]}');
if(r.response=="success"){
var usr = r.data;
console.log(usr.id);
}
The above outputs undefined.
var r = JSON.parse('{"response":"success","data":[{"id":"2"}]}');
if(r.response=="success"){
var usr = r.data;
for(var k in usr){
if(usr.hasOwnProperty(k)){
console.log(usr.k);
}
}
}
The above outputs undefined.
var r = JSON.parse('{"response":"success","data":[{"id":"2"}]}');
if(r.response=="success"){
var usr = r.data;
var ret = [];
for(var key in usr){
ret.push(key);
}
console.log(ret);
}
The above outputs 0.
var r = JSON.parse('{"response":"success","data":[{"id":"2"}]}');
if(r.response=="success"){
var usr = JSON.parse(r.data);
console.log(usr.id);
}
The above outputs an error - bear in mind this is running via Nativescript so the simulation environment (Android Emulator) may be causing this error:
chromium: [INFO:library_loader_hooks.cc(120)] Chromium logging enabled: level = 0, default verbosity = 0
01-26 19:20:55.423 4875 4875 I BrowserStartupController: Initializing chromium process, singleProcess=true
chromium: [WARNING:resource_bundle.cc(285)] locale_file_path.empty()
01-26 19:20:55.441 4875 4875 E DataReductionProxySettingListener: No DRP key due to exception:java.lang.ClassNotFoundException: com.android.webview.chromium.Drp
chromium: [WARNING:data_reduction_proxy_config.cc(423)] SPDY proxy OFF at startup
Question
How can I access the id property of data in the following JSON string with JavaScript:
{"response":"success","data":[{"id":"2"}]}
You can try with following code. You firstly need to access the data property and then since data is an array, you need an index to access the first elements like data[0] Property and then the id property can be retrieved by r.data[0].id
var r = JSON.parse('{"response":"success","data":[{"id":"2"}]}');
if(r.response === "success"){
console.log(r.data[0].id)
}
You can access console.log(usr[0].id);
Your data value is an array not an object
so on your first attempt, update this:
console.log(usr.id);
to this:
console.log(usr[0].id);
Or you could do a for loop:
if(r.response=="success"){
var usr = r.data;
for(i=0; i < usr.length; i++) {
console.log(usr[i].id);
}
}
Fiddle
Your data object is an array, so you must access first to the position of the array:
usr[0]
the you get the id value
usr[0].id
If you want to access directly with usr.id you need change your JSON data object array to a simple object:
{"response":"success","data":{"id":"2"}}
or make an ugly reasignation:
usr = usr[0]
This is because you have used [] where {} only to be used. If [] is used, then it is an array property, then to access 2, [0].id should be used.
remove [] from [{"id":"2"}]

TaffyDB not querying record

When trying to query a variety of records in the database, using the below array, TaffyDB will not lookup the record correctly.
Syntactically, it appears to be sound and should query and return the value of the record, but I assume I'm missing some fatal point.
$(".cat").each(function(){
$this = $(this);
var db = ($this.data("category")).toString()
var fn = window[db];
if (typeof fn === "function") fn().each(function(r){
var parts = ["cpu", "mobo", "ram", "gpu", "sc", "hdd", "ssd", "psu", "case", "cooler", "os"];
var pmup = "";
for(i=0;i<parts.length;i++){
var part = r.parts[i];
console.log(part) // returns: Uncaught TypeError: Cannot read property '0' of undefined
}
}
});
Using
part = r[parts[i]];
instead of
part = r.parts[i]
solves the syntax error.

Javascript List clarification

var list = {};
list[19] = 'kapooya';
list[20] = 'apples';
delete list[19];
Does
list[19] == 'apples' or null?
var list = {};
list[19] = 'kapooya';
list[20] = 'apples';
delete list[19];
( var list[xx] would not work due to syntax error )
list[19] would be undefined.
Apart from the syntax error you get when using varbefore list[19] = 'kapooya', list[19] is undefined after the delete, not null.
Technically you are not creating a list but an object, or a map, or a hash, or a dictionary, however you wish to refer to it.
The correct syntax for working with lists, or in the case of javascript, Arrays, is var list= []; be aware that the delete operator doesn't work on array items.

Categories