Handler is working with my code but it shouldn't alert when the the value is not null. I got an alert in either situations. I don't know what went wrong .
var data = {};
var deviceId = ["asdfa23", "asdfa32"]
data[deviceId] = "asdfasdf";
try {
if(data[deviceId].value == null)
throw "this is null"
}
catch(err) {
alert(err)
}
Just replace your in your if statements :
(data[deviceId].value == null)
by :
(data[deviceId] == null)
You don't have value field, it is not an object.
You can do .some() method to check a condition over an array.
var data = {};
var deviceId = "thermoment123";
data[deviceId] = ["er213", "er243"];
for(var device in data){
try{
var bool = data[deviceId].some(function(elm){
return elm
? true
: false
});
if (!bool){
var errorSensor = "The sensor "+ deviceId + " has no data"
throw errorSensor;
}
} catch(err){
alert(err)
}
}
You assign an array to data[deviceId].
The array has two properties 0 and 1 (along with all the inherited properties like forEach and length).
value is not a property of normal arrays and you haven't added one.
you have a couple syntax errors in your code:
var data = {};
var deviceId = "thermoment123";
data[deviceId] = ["er213", "er243"];
for (var device in data) {
try {
if (data[deviceId] == null) { //removed the .value
var errorSensor = "The sensor " + data[deviceId] + " has no data"; //added ';'
throw errorSensor;
} //close brackets that start at from if statement
} catch (err) {
alert(err); //added ';'
}
}
Related
First of all I'm beginner in javascript. I have this data data.responseJSOn.errors -
Currently I'm displaying the errors like this way -
var errors = data.responseJSON.errors;
console.log(errors);
errors.title &&
errors.title.forEach(function(messageText) {
displayError(messageText);
});
errors.message &&
errors.message.forEach(function(messageText) {
displayError(messageText);
});
How can I display errors from there by using single code instead of predefined errors.title or errors.message.
expected code like -
var errors = data.responseJSON.errors;
var list = ["title", "message"];
list.forEach(function(item) {
errors.item &&
errors.item.forEach(function(messageText) {
displayError(messageText);
});
});
How can I fix it to get output.
You can try something more generic regardless of the key names in object data.responseJSON.errors
var errors = data.responseJSON.errors;
var list = ["title", "message"]; // valid keys for which we need to show message
for (key in errors) {
// check if key is valid and is array
if(list.includes(key) && Array.isArray(errors[key])) {
errors[key].map((msg) => {
displayError(msg);
})
}
}
In the case you're going to need the [] syntax to access a field of the errors object with the value of a variable:
var errors = data.responseJSON.errors;
var list = ["title", "message"];
list.forEach(function(item) {
errors[item] &&
errors[item].forEach(function(messageText) {
displayError(messageText);
});
});
You can access the respective property using []:
var errors = data.responseJSON.errors;
var list = ["title", "message"];
list.forEach(function(item) {
errors[item] &&
errors[item].forEach(function(messageText) {
displayError(messageText);
});
});
Otherwise (and as a better alternative), you can use the for...in loop syntax to access enumerable object properties:
var errors = data.responseJSON.errors;
var list = ["title", "message"];
errors.forEach(function(error) {
for (property in error) {
displayError(error[property]);
}
});
here you don't have to explicitly mention the type of keys the error message has. Even in future, if messages and title changes you don't have to modify the code again.
const messageText = (message: string) => {
console.log('message', message)
}
Object.keys(response).map((error) => response[error].length && response[error].forEach((message: string) => messageText(message)));
I have function that creates a team and puts data to database. Now I'm trying to check if team already exists, if it does exists then reply with message. I have problem with my if statement.
if (result[0].teamname == teamName)
When result[0].teamname is undefined it shows Cannot read property 'teamname' of undefined it ignores else and throws an error. How can I make so that does not ignore else?
Here is the function I use to create team.
function createTeam(teamName, members, message) {
teamName = teamName.replace("_", " ");
let insertTeam = `INSERT INTO teams (teamname) VALUES ('${teamName}');`;
db.select(`SELECT id_t, teamname FROM teams WHERE teamname = '${teamName}'`, function(err, result) {
if (err) {
throw err;
} else {
if (result[0].teamname == teamName) {
if (message.guild !== null) message.delete();
message.reply("this team already exists!");
} else {
db.query(insertTeam);
db.select(`SELECT id_t FROM teams WHERE teamname = '${teamName}'`, function(err, result) {
if (err) {
throw err;
} else {
for (let i = 0; i < members.length; i++) db.query(`INSERT INTO team_user (user, team) VALUES ('${members[i]}' , ${result[0].id_t})`);
}
});
if (message.guild !== null) message.delete();
let newTeam = new Discord.RichEmbed()
.setThumbnail("https://cdn.discordapp.com/emojis/542789472421675028.png?v=1")
.setColor("#15f153")
.addField("New team has been created!", `Team ${teamName} has been created with total of ${members.length} members!\nGood luck!`);
message.channel.send(newTeam);
}
}
});
What have I tried so far:
Checking if result[0].teamname is undefined
Checking if result length is not 0
try-catch statement
if (result[0] && result[0].teamname == teamName)
First of all you need to check if result[0] is not undefined
You need to short-circuit the condition. All this means is you want to first check that result exists before checking properties of result
So for example, your code should look like this:
if (result && result[0] && result[0].teamname == teamName) {
//Do something
}
If result is array with more then one value, then you need to iterate over every one of them, you can use filter array method for this:
var found = result.filter((row) => row.teamname == teamName);
if (found.length) {
}
You can also as #ThomasKleßen mention in comment check if result is not undefined:
var found = result && result.filter((row) => row.teamname == teamName).length;
if (found) {
}
You can always do a default value
if ((result || [{}])[0].teamname == teamName)
If the result is falsy, it will default to an array of an empty object, which will allow for the array access and dot notation to work, but the equality to fail.
(using Node.js)
Hi, I have an array with users (User class) on it, when I print the array with console.log, it shows the content correctly and shows that it's length is 3, but when i try to get any thing from the array, it returns undefined and for *.length, it returns 0. Where's the problem?
exports.users = [];
exports.loadUsers = (callback) => {
let more = true;
let i = 0;
while(more) {
let us = _usersFolder + "us_" + i + "/";
if(fs.existsSync(us)) {
fs.readFile(path.join(us + "personal.json"), (err, data) => {
if(err) {
console.log("failed to load file!");
return;
}
let json_personal = JSON.parse(data);
this.users.push(new User(json_personal));
});
i++;
} else {
more = false;
}
}
callback();
}
exports.getUserById = (id) => {
console.log(this.users);
console.log("length: " + this.users.length);
console.log(this.users[0]);
for(let i = 0; i < this.users.length; i++) {
let u = this.users[i];
console.log(u.id);
if(u.id === id) {
return u;
}
}
return false;
}
getUserById is called in the callback, so users are already loaded.
It depends on where you are using the 'this' object. It's possible that 'this' makes reference to a different object than the one you stored the array in ('this' varies depending on the scope where you are using it).
I'd need more information to help you.
var users=[{"num":1},{"num":2},{"num":3}];
console.log(this.users);
console.log("length: " + this.users.length);
console.log(this.users[0]);
output
(3) [Object, Object, Object]
length: 3
Object {a: 1}
I hope you are defining after you print in console.
var users = [];
console.log(users);
console.log("length: " + users.length);
console.log(users[0]);
users.push(1);
users.push(2);
users.push(3);
The output of console.log() is misleading; While you log that time there was no value. After that it was added. It prints the reference of object , not the state value. So you will see current state value all the time.
I'm creating an application with ionic and firebase. I'm trying to verify if a element exists in my array, and if it does, I need to return true, else I need to return false. The problem is, it always return false, even if the item exists in firebase. Can you please tell me what is going wrong with following code?
Here's my service:
function IsReserved(id){
var ref = fb.child('/reserved/').orderByChild('product').equalTo(id);
ref.once("value").then(function(snapshot){
snapshot.forEach(function(data){
if(data.val().user === $rootScope.currentUser.$id){
console.log(data.val().user + " * " + $rootScope.currentUser.$id);
return true;
}
});
});
return false;
}
Here is my controller:
function Reservar(produto) {
if(!$rootScope.cart){
$rootScope.cart = [];
$rootScope.fprice = 0;
}
var user=$rootScope.currentUser;
var res = vm.IsReserved(produto.$id);
console.log(res);
if(res){
console.log("já reservado");
return;
}
Here is my firebase strucure:
-reserved:
--KdS2cH1OJ5MhKAV6Yio:
-product: "product1"
-user: "W30BB1RMg1XhNo9og9cMo4Gpr4S2"
Your code won't work because firebase works asynchronously.
You should use a callback function as a parameter, something like this:
function IsReserved(id, callback){
var ref = fb.child('/reserved/').orderByChild('product').equalTo(id);
ref.once("value").then(function(snapshot){
snapshot.forEach(function(data){
if(data.val().user === $rootScope.currentUser.$id){
console.log(data.val().user + " * " + $rootScope.currentUser.$id);
callback(true);
return;
}
});
});
return false; //-- This will always be executed before the code inside the .then, that's why your function always returns false
}
And on you controller, something like this:
function Reservar(produto)
{
if(!$rootScope.cart){
$rootScope.cart = [];
$rootScope.fprice = 0;
}
var user=$rootScope.currentUser;
vm.IsReserved(produto.$id, function(response){
console.log(response);
if(response){
console.log("já reservado");
}
});
}
Could you understand?
I have scoured the other question/answer for this and implemented everything and I still cannot access the values of the object. Here's the code I am using:
function apply_voucher(voucher) {
var dates = $.parseJSON($("[name='dates']").val());
var voucher_yes_no = new Array();
var voucher_reduction = new Array();
if(voucher.length > 0)
{
$.each(dates, function(room_id, these_dates) {
$.post('/multiroom/check_voucher/'+voucher+'/'+room_id, function(result) {
if(result.result == 'ok') {
voucher_yes_no.push('yes');
voucher_reduction.push(result.voucher_reduction);
} else {
voucher_yes_no.push('no');
}
}, 'json');
});
// check if there are any yes's in the array
if('yes' in voucher_yes_no) {
console.log("no yes's");
} else {
console.log(voucher_reduction);
console.log(typeof voucher_reduction);
for (var prop in voucher_reduction) {
console.log(prop);
console.log(voucher_reduction[prop]);
if (voucher_reduction.hasOwnProperty(prop)) {
console.log("prop: " + prop + " value: " + voucher_reduction[prop]);
}
}
}
}
}
Apologies for the constant console logging - I'm just trying to track everything to make sure it's all doing what it should. The console output I get from this is below:
...which shows the object containing one value, "1.01" and my console.log of the typeof it to make sure it is actually an object (as I thought I was going mad at one point). After this there is nothing from inside the for-in loop. I have tried jquery's $.each() also to no avail. I can't understand why nothing I'm trying is working!
It does not work because the Ajax call is asynchronous!
You are reading the values BEFORE it is populated!
Move the code in and watch it magically start working since it will run after you actually populate the Array!
function apply_voucher(voucher) {
var room_id = "169";
var dates = $.parseJSON($("[name='dates']").val());
var voucher_reduction = new Array();
$.post('/multiroom/check_voucher/'+voucher+'/'+room_id, function(result) {
if(result.result == 'ok') {
voucher_reduction.push(result.voucher_reduction);
}
console.log(voucher_reduction);
console.log(typeof voucher_reduction);
for (var prop in voucher_reduction) {
console.log(prop);
console.log(voucher_reduction[prop]);
if (voucher_reduction.hasOwnProperty(prop)) {
console.log("prop: " + prop + " value: " + voucher_reduction[prop]);
}
}
}, 'json');
}
From what it looks like, you plan on making that Ajax call in a loop. For this you need to wait for all of the requests to be done. You need to use when() and then(). It is answered in another question: https://stackoverflow.com/a/9865124/14104
Just to say for future viewers that changing the way I did this to use proper deferred objects and promises, which blew my head up for a while, but I got there! Thanks for all the help, particularly #epascarello for pointing me in the right direction :) As soon as I started doing it this way the arrays began behaving like arrays again as well, hooray!
Here's the final code:
function apply_voucher(voucher) {
var booking_id = $("[name='booking_id']").val();
var dates = $.parseJSON($("[name='dates']").val());
if(voucher.length > 0) {
var data = []; // the ids coming back from serviceA
var deferredA = blah(data, voucher, dates); // has to add the ids to data
deferredA.done(function() { // if blah successful...
var voucher_yes_no = data[0];
var voucher_reduction = data[1];
if(voucher_yes_no.indexOf("yes") !== -1)
{
console.log("at least one yes!");
// change value of voucher_reduction field
var reduction_total = 0;
for(var i = 0; i < voucher_reduction.length; i++) {
reduction_total += voucher_reduction[i];
}
console.log(reduction_total);
}
else
{
console.log("there are no yes's");
}
});
}
}
function blah(data, voucher, dates) {
var dfd = $.Deferred();
var voucher_yes_no = new Array();
var voucher_reduction = new Array();
var cycles = 0;
var dates_length = 0;
for(var prop in dates) {
++dates_length;
}
$.each(dates, function(room_id, these_dates) {
$.post('/multiroom/check_voucher/'+voucher+'/'+room_id, function(result) {
if(result.result == 'ok') {
voucher_reduction.push(result.voucher_reduction);
voucher_yes_no.push('yes');
} else {
voucher_yes_no.push('no');
}
++cycles;
if(cycles == dates_length) {
data.push(voucher_yes_no);
data.push(voucher_reduction);
dfd.resolve();
}
}, 'json');
});
return dfd.promise();
}
Can you show how voucher_reduction is defined?
I am wondering where the second line of the debug output comes from, the one starting with '0'.
in this line:
console.log(vouncher_reduction[prop]);
^
The name of the variable is wrong (then) and probably that is breaking your code.
I think there are no problem with your loop.
But perhaps with your object.
Are you sure what properties has enumerable ?
Try to execute this to check :
Object.getOwnPropertyDescriptor(voucher_reduction,'0');
If it return undefined, the property was not exist.