Property in object exists but is undefined - javascript

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

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>

removing objects in an object in an array javascript

I've done some research on this issue. I am trying to manipulate an array of calculated values that looks like this in the console:
{nodeVoltages: Array(11), totalPower: Array(1), xlength: Array(11)}
nodeVoltages: Array(11)
0:48
1:47.71306060387108
2:47.250273223993105
3:46.59686907269243
4:45.71876416434013
5:44.53304242029258
6:42.745236969423615
7:Complex {re: 40.38334500994142, im:1.919295696316476, __ember1513267958317: "ember368"}
8:Complex { re:39.55961661806138, im:3.8933604519196416, __ember1513267958317: "ember369"}
This array is created dynamically through some math that I've come up with so there is no input data that I can give you. I'm trying to make the above array look like this:
{nodeVoltages: Array(11), totalPower: Array(1), xlength: Array(11)}
nodeVoltages: Array(11)
0:48
1:47.71306060387108
2:47.250273223993105
3:46.59686907269243
4:45.71876416434013
5:44.53304242029258
6:42.745236969423615
7:40.38334500994142
8:39.55961661806138
Using mathjs, I was able to evaluate my expressions and dynamically add the values into an array with the array.push command and display them. However, my code breaks once the imaginary values pop up in the results of my array.
How can I remove these imaginary numbers from my array? In other words, I need to remove the "im:" parts of the values when they begin to appear before I push them to the displayed array.
I tried to do this with some code I found from a previous answer to someone else's question (How do I remove a particular element from an array in JavaScript?) splice command like this:
var nodeVoltage2 = parser.eval(expression2);
//checks if there are imaginary values and removes them
if ("im" in nodeVoltage2) {
nodeVoltage2.splice(2,1)
}
//adds value to result array for analysis
nodeVoltages.push(nodeVoltage2);
but it returns in the console that "im is not defined".
Any help is greatly appreciated!
You can use the array map function.
Basically, we loop through the array. If the item has a .re property, we take that value only. If there is no .re property, we keep the value as is.
We can either write that in shorthand, as with result using the ternary operator and arrow function, or we can write it in a slightly more verbose but traditional way, as with resultTwo
let data = [
48
,47.71306060387108
,47.250273223993105
,46.59686907269243
,45.71876416434013
,44.53304242029258
,42.745236969423615
,{re: 40.38334500994142, im:1.919295696316476, __ember1513267958317: "ember368"}
,{ re:39.55961661806138, im:3.8933604519196416, __ember1513267958317: "ember369"}
]
let result = data.map((x) => x && x.re ? x.re : x);
let resultTwo = data.map(function(elem) {
// First, we need to check that the array element is not null / undefined
// We then need to check that it has a property called re that is also not null / undefined
if (elem != null && elem.re != null) {
// Just return the property we're interested in
return elem.re;
} else {
// Return the element as is
return elem;
}
});
console.log(result);
console.log(resultTwo);

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

Is there a “not in” operator in JavaScript for checking object properties?

Is there any sort of "not in" operator in JavaScript to check if a property does not exist in an object? I couldn’t find anything about this around Google or Stack Overflow. Here’s a small snippet of code I’m working on where I need this kind of functionality:
var tutorTimes = {};
$(checked).each(function(idx){
id = $(this).attr('class');
if(id in tutorTimes){}
else{
//Rest of my logic will go here
}
});
As you can see, I’d be putting everything into the else statement. It seems wrong to me to set up an if–else statement just to use the else portion.
It seems wrong to me to set up an if/else statement just to use the else portion...
Just negate your condition, and you'll get the else logic inside the if:
if (!(id in tutorTimes)) { ... }
Personally I find
if (id in tutorTimes === false) { ... }
easier to read than
if (!(id in tutorTimes)) { ... }
but both will work.
As already said by Jordão, just negate it:
if (!(id in tutorTimes)) { ... }
Note: The above test if tutorTimes has a property with the name specified in id, anywhere in the prototype chain. For example "valueOf" in tutorTimes returns true because it is defined in Object.prototype.
If you want to test if a property doesn't exist in the current object, use hasOwnProperty:
if (!tutorTimes.hasOwnProperty(id)) { ... }
Or if you might have a key that is hasOwnPropery you can use this:
if (!Object.prototype.hasOwnProperty.call(tutorTimes,id)) { ... }
Two quick possibilities:
if(!('foo' in myObj)) { ... }
or
if(myObj['foo'] === undefined) { ... }
you can set the condition to be false
if ((id in tutorTimes === false)) { ... }
if(!tutorTimes[id]){ ./*do xx */.. }

catch null object in js

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';
}

Categories