JavaScript variable remains undefined - javascript

I am struggling with my webpage. The JavaScript isn't doing what it should because a variable[] isn't being populated! Please consider my code:
var datasets = { "DataItem1": {
label: "Idle Count",
dataSeries: [[13, 75.72],[13, 1],[13, 0.17],[13, 55.72],[13, 90.72],[13, 91.06]],
Threshold_0: [[134, 1],[133, 1]],
Threshold_2: [[133, 1],[131, 1]]
}
};
var data = [];
var failedData = [];
data.push(datasets['DataItem1']['dataSeries']);
failedData.push(datasets['DataItem1']['Threshold_0']['Threshold_2']);
});
The issue is with
failedData.push(datasets['DataItem1']['Threshold_0']['Threshold_2']);
Using firebug's watch window, I can see that failedData is undefined when I add a break at this point. So, I hover the mouse over the array items on this line, and Threshold_0 has data, but Threshold_2 does not (Threshold_2 is undefined).
In the watch window, I can see that datasets[] has created all the objects as expected.
I can't see why and I'm very stuck.

Here you are trying to access the property Threshold_2 through Threshold_0, you should get it through DataItem1
failedData.push(datasets['DataItem1']['Threshold_0']['Threshold_2']);
Becomes
failedData.push(datasets['DataItem1']['Threshold_2']);

The following properties do have a value:
datasets['DataItem1']['Threshold_0'][0] == [134, 1]
datasets['DataItem1']['Threshold_0'][1] == [133, 1]
I'm not sure what you actually want to do. Maybe this is what you intend to do?
failedData.push(datasets['DataItem1']['Threshold_0']);
failedData.push(datasets['DataItem1']['Threshold_2']);
Otherwise, please describe what value(s) you want to end up in failedData.

You have a typo at the end. Remove the last });

Related

How do I change a single quote of an array.element (that is inside an object) into a double quote without creating a new array?

I was told to try and use a certain code for one of the problems I solved a while ago. I'm trying to figure it out but am coming up with nada.
Using replace(), map() etc..
This is all supposed to be done using replit and not changing the whole array as part of the 'For Fun' challenge.
const products = [
{
priceInCents: 3995,
},
{
priceInCents: 2500,
},
{
priceInCents: 8900,
},
{
priceInCents: 12500,
},
];
/* Now trying to use:
products[i].priceInDollars = $${(products[i].priceInCents * .01).toFixed(2)}
*/
/*
New
Code
*/
function addPriceInDollarsKeyToProducts(pricey)
{ for (let i = 0; i < products.length; i++)
{ for (let product = products[i];
product.priceInDollars = `$${(product.priceInCents * .01).toFixed(2)}`; )
break;
}
}
addPriceInDollarsKeyToProducts();
console.log(products)
Running this snippet btw makes it seem like it's okay.
For example: I want products[0].priceInDollars to be "$39.95",
but instead I get '$39.95',
Snippet runs it as "$39.95"
I'm not supposed to recreate the whole entire array.
If the code doesn't match the double quote requirements I get TypeError: Cannot read property '0' of undefined
edited for clarification purposes
Alright, a friend caught the problem.
I never reinserted my return like a dumb dumb.
Here I was going crazy trying to make a '"$39.95"' into a "$39.95" via replace(), map(), creating a replace function and what not when it was simply that I needed to add
return products;
at the end between the ending }

Return value for function is not working correctly. How to set up correct return value for function checkIfExist()?

I am writing a script for Premiere pro where I can add markers in the timeline and export a still for each marker in one go. However, when I write a function to check if the still has been previously created, the functions tells me it finds the previously created still, but then still creates a new one.
So basically: Function returns true, but still executes the else{}
//checks if the frame that is about to be exported already exists
if(checkIfExist(app.project.rootItem, outputFile)){
alert("frame already exists");
}else{
//This is where the actual still gets created and imported
activeSequence.exportFramePNG(time, outputFileName);
//here the previously created item gets moved to the appropriate bin (This is working great ATM)
moveToBin(outputFile);
}
}
}
//This function is meant to check if an item exists in the project bin. It does this by looping though all the items in the array from the start.
function checkIfExist(currentItem, name){
for(var i = 0; i<currentItem.children.numItems; i++){
currentChild = currentItem.children[i];
if(currentChild.name.toUpperCase() === name.toUpperCase()){
alert("Found: " + currentChild.name);
return true;
}if(currentChild.type == ProjectItemType.BIN){
checkIfExist(currentChild, name);
}
}
return false;
}
I think it happens because of the recursion you do:
if(currentChild.type == ProjectItemType.BIN){
checkIfExist(currentChild, name);
}
If this one gets kicked off before you can return true, you will start to run the function for a second time.
Now the first run can return a true, while the second (or even 3th, or 4th, etc) can return false and thus creating a new one, while also finding it.
Also if possible try to use arr.find or arr.findIndex and check if the value is -1 (or not found). This will make your code shorter, cleaner and less open for errors :)
But this will not work for nested arrays. Then you need to make an other function to first make a flat copy that includes all nested array before you do the arr.find or arr.findIndex. Still think that is the better solution.
You can use this to make nested array into a flat one:
let arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
function flattenDeep(arr1) {
return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}
flattenDeep(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]

D3 append is not a function when using with VueJS and Vuex

I have a html 'div' and I am trying to append another div to it by the following :
var myDiv = d3.select("#container")
myDiv.append("div")
And I get the following error :
myDiv .append is not a function
Any ideas ? I am using Vuex, so I instantiated the variable in the store and trying to set it to the d3 select.
I have put together a codepen that's similar to what I have : https://codepen.io/anon/pen/oMBGmd?editors=1010
const store = new Vuex.Store({
state: {
networkVariables: {
node: "",
data: [1, 2, 3, 4, 5]
},
container: ""
},
getters: {},
mutations: {}
});
console.log("line 33");
console.log(store);
var networkVariables = store.state.networkVariables;
var container = store.state.container;
container = d3.select("#container");
console.log(networkVariables);
networkVariables.node = container
.selectAll(".node")
.data(networkVariables.data);
console.log(networkVariables.node);
networkVariables.nodeEnter = networkVariables.node.append("div");
In your latest codepen, the error you mentioned is coming from the last line, where you are trying to append to the networkVariable.node directly -- without using the enter selection.
It seems to work for me when I change the last line to be:
networkVariables.nodeEnter = networkVariables.node.enter();
networkVariables.nodeEnter.append("div");
Here networkVariables.nodeEnter = networkVariables.node.append("div");, there is no append() in networkVariables.node object. I tried replacing networkVariables.node.append() with networkVariables.node[0].parentNode.append("div"), this seems to work in the snippet. can you try with this change.
The line in the codepen with the error is like #SteveR noticed the last line.
It is not the result of a d3.select() but a d3.selectAll(..).data(...). The array contains 5 empty placeholders and two fields. These are enter and exit, both functions. To convert this to a "selection" result you have to call one of these functions first before you can append().
But in the original question there should be no problem appending if the tag with the given id exists.
The codepen is not similar to the original question/example.

I'm trying to use jquery to create a div containing columns but I can't get my array to format correctly

I have an array that contains dates. and for some reason I can't get it to show on my screen I've been debugging for a few days now and I've tracked it down to a single line, but the line has worked before and I can't figure out what the issue might be.
The array looks like this:
var selectItems =
[ "05-26-2017", "06-02-2017", "06-09-2017",
"06-16-2017", "06-23-2017", "06-30-2017", "07-07-2017", "07-14-2017",
"07-21-2017", "07-28-2017"...];
It's passed as an argument from another function, but that's how it's showing in console.log().
I might be going about this the wrong way, maybe even a lot further around then I need to but this is what I've come up with:
1. function setTHead(selectItems) {
2 var formatString;
3. for (var x = 0; x < 12; x++) {
4. formatString = selectItems[x].replace(/[^0-9/-]/g, "").toString();
5. console.log(selectItems);
6. $('#datTab').append("<div id='col" + x + "' class='column'>'" + formatString + "'</div>");
7. }
8. }
the array up top is what's showing from the console.log 5 lines down.
the sixth line is what is seeming to give me issues. Nothing is put on the page at all.
I'm getting a console error saying:
jQuery.Deferred exception: selectItems is undefined setTHead#http://localhost/mySite/script.js:136:9
startUp2#http://localhost/mySite/script.js:146:5
#http://localhost/mySite/table.php:19:9
mightThrow#http://localhost/mySite/lib/jquery.js:3586:52
resolve/</process<#http://localhost/mySite/lib/jquery.js:3654:49
setTimeout handler*resolve/<#http://localhost/mySite/lib/jquery.js:3692:37
fire#http://localhost/mySite/lib/jquery.js:3320:30
fireWith#http://localhost/mySite/lib/jquery.js:3450:29
fire#http://localhost/mySite/lib/jquery.js:3458:21
fire#http://localhost/mySite/lib/jquery.js:3320:30
fireWith#http://localhost/mySite/lib/jquery.js:3450:29
ready#http://localhost/mySite/lib/jquery.js:3923:13
completed#http://localhost/mySite/lib/jquery.js:3933:9
EventListener.handleEvent*#http://localhost/mySite/lib/jquery.js:3949:9
#http://localhost/mySite/lib/jquery.js:39:9
#http://localhost/mySite/lib/jquery.js:17:3
undefined
followed by:
TypeError: selectItems is undefined
and thats pointing to line 6.
if anyone has any advice I would be very much appreciative. Thank you in advance.
EDIT: A little more code:
function startTblView(defSel) {
if (defSel === true) {
setCookie('defSel', true, 7);
} else{
setCookie('defSel', false, 7);
}
saveSelected();
window.open('table.php', '_self');
defSel = getCookie('defSel');
if (defSel) {
selectItems = getDefDates();
}else {
selectItems = reGetSelected();
}
setTHead(selectItems);
}
defSel, is a boolean passed from my last page stating whether I'm doing a default view or a custom view, the custom view is passed from saveSelected();
saveSelected is a function for just saving the selected global value as a cookie so I can pull it out on the next page.
getDefDates pulls the default values for the array
reGetSelected, gets the selected array from the cookie.
I apologize for wonky naming conventions. I'm the only one working on this site and I'm just making sure the names don't overlap.
You can do this :
HTML code
<div id="datTab"></div>
JS code
var selectItems =
[ "05-26-2017", "06-02-2017", "06-09-2017",
"06-16-2017", "06-23-2017", "06-30-2017", "07-07-2017", "07-14-2017",
"07-21-2017", "07-28-2017"];
function setTHead(selectItems) {
var formatString;
$.each( selectItems, function( index, value ){
formatString = value.replace(/[^0-9/-]/g, "").toString();
$('#datTab').append("<div id='col" + index + "' class='column'>'" + value + "'</div>");
});
};
You can use $.each, its better than 'for' with javascript.
The .each() method is designed to make DOM looping constructs concise
and less error-prone. When called it iterates over the DOM elements
that are part of the jQuery object. Each time the callback runs, it is
passed the current loop iteration, beginning from 0. More importantly,
the callback is fired in the context of the current DOM element, so
the keyword this refers to the element.
I did a JsFiddle
Here.

How can I compare a string to an object key and get that key's value?

I want to do something relatively simple, I think anyways.
I need to compare the pathname of page with an object's kv pairs. For example:
if("pathname" === "key"){return value;}
That's pretty much it. I'm not sure how to do it in either regular Javascript or jQuery. Either are acceptable.
You can see my fiddle here: http://jsfiddle.net/lz430/2rhds1x3/
JavaScript:
var pageID = "/electrical-electronic-tape/c/864";
var pageList = [{
"/electrical-electronic-tape/c/864": "ElectronicTape",
"/industrial-tape/c/889": "IndustrialTape",
"/sandblasting-tape/c/900": "SandblastingTape",
"/Foam-Tape/c/875": "FoamTape",
"/double-coated-d-c-dhesive-tape/c/872": "DCTape",
"/Adhesive-Transfer-Tape/c/919": "ATTape",
"/Reflective-Tape/c/884": "ReflectiveTape",
"/custom-moulding": "CustomMoulding",
"/request-a-quote": "RequestQuote"
}];
var label = pageID in pageList;
$('.el').html(label);
First, your "pageList" should just be a plain object, not an object in an array:
var pageList = {
"/electrical-electronic-tape/c/864": "ElectronicTape",
"/industrial-tape/c/889": "IndustrialTape",
"/sandblasting-tape/c/900": "SandblastingTape",
"/Foam-Tape/c/875": "FoamTape",
"/double-coated-d-c-dhesive-tape/c/872": "DCTape",
"/Adhesive-Transfer-Tape/c/919": "ATTape",
"/Reflective-Tape/c/884": "ReflectiveTape",
"/custom-moulding": "CustomMoulding",
"/request-a-quote": "RequestQuote"
};
Then you can set "label" to the value from the mapping:
var label = pageList[pageID] || "(not found)";
That last bit of the statement above will set the label to "(not found)" if the lookup fails, which may or may not be applicable to your situation.
It depends kinda on the logic you want to implement. If you want to say "if object has the key, then do X, and if not, then do Y", then you handle that differently than "set label to the object's key's value if the key is there, or else set it to undefined or something else".
For the first case you do:
if (pageList.hasOwnProperty(pageID) ) {
label = pageList[pageID];
}
else {
// do whatever, maybe some error?
}
For the second case, you can just say
var label = pageList[pageID] || 'notFound';
As indicated by #Pointy, either get rid of the array or subsiture pageList[0] for pageList and pageList[0][pageID] for pageList[pageID] above, if you need to keep the array.

Categories

Resources