TaffyDB not querying record - javascript

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.

Related

TypeError: Cannot set property '2' of undefined (line 24, file "Code")

I've been trying to figure out this but for the longest time and I've got nothing. How do I fix this error, please help
function myFunction() {
var form = FormApp.openByUrl('form');
var allItems = form.getItems();
var doc = SpreadsheetApp.getActiveSpreadsheet()
var sheet = doc.getSheetByName("name");
var last = doc.getLastRow();
var data = sheet.getRange(1,1,last,8).getValues();
for(i=0,h=1; i<data.length, h<allItems.length;++i,++h){
if(data[i][2] == 0 && h==4){ //this where the error messages comes up for the "2"
var newText = allItems[h].asMultipleChoiceItem();
var title = newText.getTitle();
var newTitle = newText.setTitle(title+" (Sold out)");
}
}
}
It means i exceeds data.length=> data[i] will be undefined =>undefined[2]: Well,undefined doesn't have property [2].
TypeError: Cannot set property '2' of undefined
The "condition" of the for-loop seems amiss. The comma operator only returns the last value. Try
i<data.length && h<allItems.length
instead.

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

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.

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"}]

How to skip if substring is null and avoid error in console?

Grab the substring:
var hash = document.location.hash;
// create an object to act like a dictionary to store each value indexed by its key
var partDic = {};
// remove the leading "#" and split into parts
var parts = hash.substring(1).split('&');
// If you just want the first value, whatever it is, use this.
// But be aware it's a URL so can be set to anything in any order, so this makes little sense
// var string = parts[0].split('=')[1];
// build the dictionary from each part
$.each(parts, function(i, v) {
// do the "=" split now
var arr = v.split("=");
// decode to turn "%5B" back into "[" etc
var key = decodeURIComponent(arr[0]);
var value = decodeURIComponent(arr[1]);
// store in our "dictionary" object
partDic[key] = value;
});
// Set a delay to wait for content to fully load
setTimeout( function() {
var ag = partDic["comboFilters[Agencies]"].substring(1);
$('.Agency .dropdown-toggle').html(ag).append(' <span class="caret"></span>');
var cl = partDic["comboFilters[Clients]"].substring(1);
$('.Client .dropdown-toggle').html(cl).append(' <span class="caret"></span>');
var yr = partDic["comboFilters[Years]"].substring(1).slice(1);
$('.Year .dropdown-toggle').html(yr).append(' <span class="caret"></span>');
}, 1000);
But if there is not a substring, I am getting:
Uncaught TypeError: Cannot read property 'substring' of undefined
Suggested answer in another question
var cl = (partDic["comboFilters[Clients]"] && partDic["comboFilters[Clients]"].length>0)?partDic["comboFilters[Clients]"].substring(1):'';
But I still get the same error
You can be defensive and check if a key exists before using it:
if("comboFilters[Agencies]" in partDic) {
var ag = partDic["comboFilters[Agencies]"].substring(1);
$('.Agency .dropdown-toggle').html(ag).append(' <span class="caret"></span>');
}
or just safeguard it with an empty string:
var ag = (partDic["comboFilters[Agencies]"] || "").substring(1);
Maybe try with things like:
var parts = (hash && hash.substring(1).split('&')) || [];
You can try to check it's type:
var cl = (typeof partDic["comboFilters[Clients]"] === 'string')?partDic["comboFilters[Clients]"].substring(1):'';
Note, that you should add this check for all your variables: ag, cl, yr
You can check one condition before using substring method..
if((!hash) || (!hash.substring(1)){
return false;
}

Check if JSON keys/nodes exist

I'm using the Google Map API to retrieve city + state/region information from a postal code lookup. The issue is that in some cases a postal code lookup won't retrieve a city name. An example is 92625 (U.S).
var g = new GClientGeocoder();
g.setBaseCountryCode('US');
g.getLocations('92625', function(response){
if (response) {
var place = response.Placemark[0];
var state = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
var city = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
GLog.write("City = "+city+" : State/Region = "+state+" : Country = " + g.getBaseCountryCode());
}
});
In certain cases, as mentioned above, there won't be a city name in the result so there will be an undefined error for city, because the key Locality does not exist. This error prevents the rest of the script from running.
I was able to remedy it by...
if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality != null)
var city = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
else
var city = '';
...but this has me paranoid about a similar error for other keys. Eg: If AdministrativeArea is undefined the above IF statement would also cause an undefined error. So should I be checking to see if every Key/Node exists? Seems to be a messy approach because some of these keys are 5+ levels deep...is there an easier way to go about it, maybe some JQuery method I'm not familiar with?
Alternatively, you could make a function, that gives you defaults:
function valueOrDefault(val, def) {
if (def == undefined) def = "";
return val == undefined ? def : val;
}
And then use it like this:
var place = response.Placemark[0];
var state = valueOrDefault(place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName);
var city = valueOrDefault(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName);
Personally, I think it's a little nicer to write, than p00ya's proposal, although it's a little hacky fiddling around in undefined objects ... one could maybe change it to this:
function drill(p, a) {
a = a.split(".");//add this
for (i in a) {
var key = a[i];
if (p[key] == null)
return '';
p = p[key];
}
return p;
}
var obj = {foo:{bar:{baz:"quux"}}};
var s = drill(obj, "foo.bar.baz"));//and you can use a simple property chain
You could use a function that "drills" down through all those nesting levels, defaulting to the empty string if it can't get that far.
function drill(p, a) {
for (i in a) {
var key = a[i];
if (p[key] == null)
return '';
p = p[key];
}
return p;
}
var obj = {foo:{bar:{baz:"quux"}}};
var s = drill(obj, ["foo", "bar", "baz"]));
I like back2dos' approach but I think it could be improved so as not to fail with ReferenceErrors:
function jPath(obj, a) {
a = a.split(".");
var p = obj||{};
for (var i in a) {
if (p === null || typeof p[a[i]] === 'undefined') return null;
p = p[a[i]];
}
return p;
}
// Tests
var a = {b:{c:'Hello World!'}, c:null};
console.log(jPath(a, 'b.c')); // Hello World
console.log(jPath(a, 'b.d')); // null
console.log(jPath(a, 'e.f.g')); // null
console.log(jPath(a, 'c')); // null
var z;
console.log(jPath(z, 'c')); // null
This kind of function is great for validating deep JSON return structures from AJAX services such as freebase or YQL.
You are looking at only the first result the geocoder gives you:
var place = response.Placemark[0];
getLocations() returns a list of several results. If the first one doesn't have it, one of the next few results almost certainly will.

Categories