catch null object in js - javascript

How can i catch the object is null or not an object. Actually i have wrote this line in if condition for solving it, but not working.
But Generating ERROR :- "object is null or not an object"
var preWynum = "";
function paint(Wynum)
{
// alert("Wynum:"+Wynum +", preWynum:"+preWynum);
if(document.getElementById(preWynum) && document.getElementById(Wynum))
{
document.getElementById(preWynum).style.backgroundColor='white';
document.getElementById(Wynum).style.backgroundColor='yellow';
}
preWynum = Wynum;
}
I dont believe why it not running.
Any other idea ?
preWynum and Wynum is the id of tr(table row).
I want to set background color with yellow to current selected row(that's id is Wynum).

The error is because you are passing an object (non-existent) to getElementById() when it expects a string:
// Put quotes around 'preWynum' and 'Wynum'
if(document.getElementById('preWynum') && document.getElementById('Wynum'))
{
document.getElementById('preWynum').style.backgroundColor='white';
document.getElementById('Wynum').style.backgroundColor='yellow';
}

Related

Skipping undefined elements from an API call

I am gathering data from an API to show the Pokemon typing. Some Pokemon have one type, while others have two.
The variables to gather the typing data are as such.
function createPokemonCard(pokemon) {
const type = pokemon.types[0].type.name;
const second_type = pokemon.types[1].type.name;
...}
And then I call them via InnerHTML in the same function with the following code.
<small class="type"><span>${type}/${second_type}</span></small>
Predictably, when it hits undefined for a Pokemon, it breaks and doesn't display the card. However I am not sure how to get it to not print the second type when it's undefined.
I thought about doing an if statement, but what should I call if there is an undefined variable?
function undefined {
if(second_type === 'undefined') {
???
}}
Or would a for loop work better? I am not sure how to get it to bypass the undefined and print nothing.
const second_type = pokemon.types[1] ? pokemon.types[1].type.name: undefined;
`<small class="type"><span>${type}${second_type!=undefined ? `/${second_type}`: ''}</span></small>`
The ? : syntax is a ternary operator (mdn)
It's a less verbose way of writing out the following:
if (second_type!=undefined) { // check if second_type is not undefined
return `/${second_type}` // if it's not return / and the second type
} else { //otherwise
return '' // return an empty string
}
If you do not want to display the trailing / when second_type is not defined one way to go could be
const type = pokemon.types.map(({ type }) => type.name).join("/")
and then
<small class="type"><span>${type}</span></small>

Understanding procedures in Snowflake (javascript)

I came through lately following line of code while analyzing 3rd party data script.
CREATE OR REPLACE PROCEDURE WH.SCHEMA.PROCEDURE_NAME(DATE_OF_LOAD STRING) --input which will be binded later
RETURNS STRING
LANGUAGE javascript
AS $$
var drop_table = `drop table if exists TABLE_NAME;`;
var stmt_drop_table = snowflake.createStatement( {sqlText: drop_table} );
var incremental_data =
`CREATE TABLE AS <many arguments>
WHERE P.CZAS_MODYF_SF >= :1 --this is where biding of DATE_OF_LOAD occurs)
SELECT *, HASH(*) HASH FROM (
SELECT <arguments>
FROM CTE) q; `;
var stmt_incremental_data = snowflake.createStatement( {sqlText: incremental_data,binds: [DATE_OF_LOAD ].map(function(x){return x === undefined ? null : x}) } );
try {
stmt_drop_table.execute();
stmt_incremental_data.execute();
rtr = "Success!";
return rtr;
}
catch (err) {
return "Failed: " + err;
}
$$
;
Entire challenge I have is with:
var stmt_incremental_data = snowflake.createStatement( {sqlText: incremental_data,binds: [DATE_OF_LOAD ].map(function(x){return x === undefined ? null : x}) } ).
object.method part is clear. Same for binds. Code after binds is my issue here.
Another topic: Snowflake interpretes method's parameters as a JSON. Does it mean that bind value can be extended by assigning JS code?
I'll be greatly thankful for help and explanation.
The reason I did not post this as an answer initially is that JavaScript is not my area of expertise. I did dabble in it for a few months.
But in order to understand what is going on with:
[DATE_OF_LOAD ].map(function(x){return x === undefined ? null : x})
You need to break it down:
x === undefined ? null : x
This is called an elvis operator and is the equivalent of :
if (x === undefined)
{
return null
} else {
return x
}
Now that we know what the function does, we need to understand the map method. But in short it creates a new array with the results of calling a provided function on every element in the calling array.
So the simple answer copied from my comment is:
if DATE_OF_LOAD is undefined it will replace it with null, otherwise it will use whatever value is stored in DATE_OF_LOAD. That is because SQL does not know how to handle undefined.
But here is the reasoning for my answer.

Angularjs add new field in for loop error

I am trying to add a new "field" ( not sure if it's called as field ) in an array,
but it stops at a certain number. For example, I have 33 objects in the array, it stops at the 7th object.
My JS:
if ($scope.all[i].CATEGORY == 'Community')
{
$scope.community.push($scope.all[i]);
$scope.community[i].visibility = true;
console.log($scope.community[i])
}
The error it throws me
PS: Visibility doesn't exist in my object, I am adding it in
More info :
When i console log the whole array it returns me with 33 object
if ($scope.all[i].CATEGORY == 'Community')
{
$scope.community.push($scope.all[i]);
console.log($scope.community)
}
But when i console log it with the [i] loop
if ($scope.all[i].CATEGORY == 'Community')
{
$scope.community.push($scope.all[i]);
console.log($scope.community[i]) <----
}
I get 6 returns with 27 undefined returns ..
Some of the Objects does not have a property named visiblility , you should be able to handle with the following code,
if ($scope.all[i].CATEGORY == 'Community')
{
$scope.community.push($scope.all[i]);
if($scope.community && $scope.community[i]){
$scope.community[i].visibility = true;
console.log($scope.community[i])
}
}

Function to conditionally assign variable member data to nested array in object?

I want to add data into an object, and my object contains nested data. Example data:
pageviewEvent {
client: "clientName",
page {
document_referrer: 'some http refer header data goes here',
window_height: 1920,
window_width: 1200
}
}
Some data is undefined or null and I do not want to add this undefined/null data into the object.
I made a function that works to add data to the object conditionally (if not undefined) but I can't figure out how to add data to nested objects in the function?
I could just make a bunch of if statements, but figure it's better to put the condition test into a function to reduce code size.
Example code with comment showing thinking of what I am trying but doesn't work:
//function to check if variable undefined or null, if not -> add to pageviewEvent arrayKey, variableName
function isUndefinedNull(arrayKey, variableName) {
var evalVariableName = eval(variableName);
if (evalVariableName !== undefined && evalVariableName !== null && evalVariableName !== "") {
console.log(arrayKey);
console.log(variableName);
pageviewEvent[arrayKey] = evalVariableName;
//array key could be nested, for instance pageview[page][title] or pageview.page.tile
}
}
//make event array
const pageviewEvent = { }
//add static data
pageviewEvent.client = 'neguse';
//if not null or undefined add data
isUndefinedNull('referrer.full', 'document.referrer');
//want to put data into object pageviewEvent.referrer.full or pageviewEvent[referrer][full]
Thanks for any help. I feel like this answer can help but I can't figure it out.
I recommend using the lodash function _.set(), documentation can be found here: https://lodash.com/docs/4.17.4#set
_.set( pageviewEvent, "referrer.full", "some-value" );
If you want to customise the behaviour of how nesting is handled when there's an undefined value, you can instead use _.setWith() - see https://lodash.com/docs/4.17.4#setWith

Property in object exists but is undefined

I have an object that in javascript that does have the property that I'm looking for, but when I try to access the property it's undefined.
Here is my code:
for (ret of value.methods[values[1]].ret) {
var names = Object.keys(ret)
console.log(JSON.stringify(ret, null, 2))
if (names[0] == "N/A") {
methodString = methodString.concat(` ${ret.type}`);
}
else {
methodString = methodString.concat(` ${names[0]} (${ret.type}),`);
}
}
On the 3rd line of the code sample above I'm printing out the object and this is the console output
{
"newPosition": {
"type": "table"
}
}
So type does exist inside of newPosition but when I try to access it on either line 5 or line 8 it says it's undefined. When checking if the property exists with hasOwnProperty member function it returns false.
I'm really stumped by this and I don't know what to do. I've looked at a lot of answers here on stack overflow and none of them have provided me with an answer to this problem.
The issue is that ret.type is undefined.
What you're trying to get isret.newPosition.type

Categories