When I run my code it returns my value as undefined which is strange because if I run the entire array it shows all data.
Here is the code:
console.log(appid_cards[x].cards); (returns "undefined")
console.log(appid_cards[x].appid); (returns "undefined")
console.log(appid_cards[x]); (returns "appid=", "cards:")
for example this happens if I run a specific (existing row) :
console.log(appid_cards[x].cards); (returns "undefined")
console.log(appid_cards[x].appid); (returns "undefined")
console.log(appid_cards[x]); (returns "appid: 400250, cards: 8")
console.log(x); (returns "0")
so the X works for the entire RowDataPacket, but if I want to select a key then it somehow doesn't work.
I also check if maybe x would become greated then the number of rows but that is no the case because it is run in a "for" loop and it cannot be greater than appid_cards.length, I can call the entire array but once I start to specify the "cards" or "appid" it returns undefined.
Thanks for the help.
Found out that where I pushed the array something went wrong and fixed that piece of code, fixing this as well. Thanks for all the help !
Related
Hopefully, my codepen is clear enough, first time using it - https://codepen.io/jsfo011/pen/GRojmpw
notEmpty is JSON from my database. I wrote a function to loop through it and find the row that matches a parameter, returning the value.
If my function can't find a matching row, I want to return 0.
I figured what I had written would work, but I keep getting
"jQuery.Deferred exception: Cannot read property 'total_income' of undefined" "TypeError: Cannot read property 'total_income' of undefined
But it seems to work fine when it does match.
What am I missing?
If income after filtering does not have a single value (empty list), single[0] is undefined. So, the following code was trying to access a property "total_income" of undefined
income[0]["total_income"]
You need to make sure that the property is accessed only if the parent object income[0] is valid.
One way to do this is by adding another check to make sure that income has at least a single value in the list before we access it like so:
if (income && income.length) {
if (income[0]["total_income"] !== undefined) {
return parseFloat(income[0]["total_income"]);
}
}
The line checks to make sure that income is defined and has at least one value.
Output:
Empty Data - 0
Found - 1000
Not found - 0
Hope this helps in understanding the issue.
why not just using lodash.get( ) with default value 0:
function calculate(data, income_type) {
let income = _.filter(data, {'income_type': income_type});
let incomeValue = _.get(income, '0.total_income', 0);
return parseFloat(incomeValue);
}
I have an array of objects with a length of at most 4 and at least 1. Here, I check which elements exist and do things accordingly.
function sendToGroup(receiver_group) {
if (receiver_group[0] !== undefined){
console.log(receiver_group[0])
}
if(receiver_group[1] !== undefined){
console.log(receiver_group[1])
}
if(receiver_group[2] !== undefined){
console.log(receiver_group[2])
}
if(receiver_group[3] !== undefined){
console.log(receiver_group[3])
}
}
When I give the array of 2 elements to this function, I see first and second element as expected in the console output but I also see an undefined in the line of
console.log(receiver_group[2])
How is this even possible? If it is undefined(which it is) this logging code should not get executed.
Edit: Chrome says the length of the array is 2. Which It is.
receiver_group is an array. which has the content of
[{id:12, name:"name", age:"21"}, {id:22, name:"name", age:25}]
Also same thing doesn't happen for the item 4 which has the index of 3.
It is also printing undefined, if I execute the below code:
if(1==2){}
In the console you can type a name of a variable (for example try
typing window) and it prints info about it. When you run any void
function (like console.log) from the console, it also prints out info
about the return value, undefined in this case.
So, the undefined printed after logging [0] and [1] value is the correct behavior as it is trying to print the return value which is undefined.
Please refer to the answer: Chrome/Firefox console.log always appends a line saying undefined
I'm trying to check a value in JS that on page load is returned as a single-element array and after an ajax function returns as a string. I don't know why it's doing this but I'm trying to role with it.
So, using console.log(value) I get array ['Scranton'] on page load, and the ajax even returns string "Scranton"
When trying to check this variable, this does not work as I intended:
if ( value === 'Scranton' || value === ['Scranton']){
...
}
Any help is appreciated!
This would probably work but I would try and fix the underlying issue instead of working around it.
if ( value === 'Scranton' || value[0] === 'Scranton'){
...
}
You can use indexOf for both an array and a string, so value.indexOf("Scranton") !== -1 will work (just tested this on the console).
However you must first check for null/false/undefined or it will error.
if (value && value.indexOf("Scranton") !== -1) {}
EDIT: As Felix said, this will also be true for any string containing "Scranton". If this is a problem, then you can check for indexOf == 0 instead, which will be true for any string starting with "Scranton". It really depends on your concrete problem if this solution fits you. Use with care.
if (Object.prototype.toString.call(value) === '[object Array]') {
if (value.indexOf('Scranton') != -1) {
/* */
}
} else {
if (value === 'Scranton') {
/* */
}
}
Edit 1:
First, you need to check if "value" is an array. If it's an array and contains the string "Scranton", you can find it using value.indexOf().
And if "value" is not an array, you can directly compare it with the string 'Scranton'.
What does "after an ajax function" mean? The page loads with a default variable that has been assigned an array value, and then an Ajax request is made, which changes this default variable, and instead of an array being assigned, it assigns a string? Assuming this "ajax function" changes the default variable to the response text from the server, there is your problem: Ajax--like any other request--is text-based, so it is a string. If you are responding to the Ajax request with a JSON string, built on the server, it needs to be parsed in the browser, so it can be reinterpreted as an array. See the JSON.parse method.
Please help to solve the undefined error coming in my console while running the below code
Please see this JSbin also http://jsbin.com/ONOwujA/1/edit
data = [
{key:"home",value:"hk1"},
{key:"home",value:"hk2"},
{key:"home",value:"hk3"},
{key:"home",value:"hk4"},
{key:"product",value:"pk1"},
{key:"product",value:"pk2"},
{key:"product",value:"pk3"},
{key:"product",value:"pk4"},
{key:"service",value:"sk1"},
{key:"service",value:"sk2"},
{key:"service",value:"sk3"},
{key:"service",value:"sk4"}
];
myFilteredKey=[];
for(i=0;i<=data.length;i++){
if(myFilteredKey.indexOf(data[i].key)!=-1){
myFilteredKey.push(data[i].key);
console.log(data[i].key);
}
}
Use i < data.length. If the length is 3, the maximum index is 2.
Another problem with your code is that no element will be added to myFilteredKey. Since the array is already empty, no element will satisfy the condition myFilteredKey.indexOf(data[i].key)!=-1. Maybe you want to use === -1 instead, i.e. check whether the element is not in the array rather than whether it's in the array.
The answer to this question seems like it would be obvious, but I'm always looking to improve my semantics, so bear with me.
I have an array structure with individual items containing X,Y coordinates
var example = new Array();
example.push({x:0,y:0});
In my code I have a set interval that updates my canvas and checks for certain conditions. Including one similar to this
if(example[0].x == other.x && example[0].y == other.y)
{
//do something
}
The issue is that the array is very dynamic, and when the code is first executed the example array is empty. Hence, Chrome throws errors along the lines of "Cannot get property x". To shut up the console, I added a dummy item to the array {x:"~", y:"~"} but it seems really unintuitive. Have I implemented an undesirable data structure? What's a simple way to handle if statements for objects that... don't exist?
Why don't you just check whether the array has elements?
if (example.length && ...)
Or whether the first element is true:
if (example[0] && ...)
if (0 in example
&& example[0].x == other.x && example[0].y == other.y) {
// do something
}
(This works for arbitrary index, not just 0; if you just want to check if the array is non-empty, example.length as shown by melpomene is good.)
You should be able to check on the first-level element (i.e. 'example') - JavaScript usually throws errors like this when you try to access a property of an element that is null or undefined. Like some others have already shown:
if(example[0] && example[0].x === other.x)
The point is though that JavaScript will let you have example[0] and return as you like, but once you try to access that property, you're out of luck:
var example = [];
//undefined
example
//[]
example[0]
//undefined <--- this is a falsy value, will evaluate false in a check
example[0].x
//TypeError: Cannot read property 'x' of undefined