Unable to print out a property in json - javascript

I am dynamically adding a new property(object) into the existing object.
Here is my code:
.then(transactionDetails => {
console.log(transactionDetails);
if(transactionDetails != null){
transactionDetails["nextDueDate"];
for(var i = 0; i < transactionDetails.length; i++){
if(transactionDetails[i].customers_installment_detail.installment1_isPaid === false){
nextDueDate = {
installment1_dueAmount:transactionDetails[i].customers_installment_detail.installment1_dueAmount,
installment1_dueDate:transactionDetails[i].customers_installment_detail.installment1_dueDate
}
}else if(transactionDetails[i].customers_installment_detail.installment2_isPaid === false){
nextDueDate = {
installment2_dueAmount:transactionDetails[i].customers_installment_detail.installment2_dueAmount,
installment2_dueDate:transactionDetails[i].customers_installment_detail.installment2_dueDate
}
}else if(transactionDetails[i].customers_installment_detail.installment3_isPaid === false){
nextDueDate = {
installment3_dueAmount:transactionDetails[i].customers_installment_detail.installment3_dueAmount,
installment3_dueDate:transactionDetails[i].customers_installment_detail.installment3_dueDate
}
}else if(transactionDetails[i].customers_installment_detail.installment4_isPaid === false){
nextDueDate = {
installment2_dueAmount:transactionDetails[i].customers_installment_detail.installment4_dueAmount,
installment2_dueDate:transactionDetails[i].customers_installment_detail.installment4_dueDate
}
}
transactionDetails[i]["nextDueDate"] = nextDueDate;
}
res.json({response:transactionDetails});
}else{
res.json({response:"No active transaction."});
}
})
I am dynamically adding nextDueDate. I am able to print out the value in console by typing transactionDetails[0].nextDueDate but however when I try to print it out the whole object in JSON, nextDueDate is missing and just could not be printed out. Any reasons ?

It is due to Sequelize issue according to this thread:
Add Property to Object that is returned by Sequelize FindOne
I fixed this by adding a virtual column in my model.
nextDueDate: Sequelize.VIRTUAL

Related

IF statement to identify 'null' in loop being ignored

I have the following loop which I have put together and is working (up to a point):
for (var i = 0; i < dataIn.length; i++) {
if (dataIn.YourName = [] ) {
var modifiedName = dataIn[i].YourName.replace(/ \([\s\S]*?\)/g, '');
dataIn[i].YourName = modifiedName;
}
else {
console.log('Do Nothing');
}
}
However, I run into an error when the content from the API source is empty (null).
Console error: Cannot read property 'replace' of null
As a result I have tried to update my loop to only run if the information is NOT null or undefined (see below), but it is being ignored and still trying to run.
for (var i = 0; i < dataIn.length; i++) {
if (dataIn.YourName !== null && dataIn.YourName !== '' ) {
var modifiedName = dataIn[i].YourName.replace(/ \([\s\S]*?\)/g, '');
dataIn[i].YourName = modifiedName;
}
else {
console.log('Do Nothing');
}
}
Sample data from the API.
What works:
"YourName": "John Citizen",
What throws the console error:
"YourName": null,
Let's first address an issue here. This line:
if (dataIn.YourName = [] ) {
Will always evaluate true. You are assigning an empty array to your YourName property and then using that assignment in an if - empty arrays are always truthy.
As to how you've tried to correct it, you're checking initially dataIn.YourName but then trying to read dataIn[i].YourName - you need to be consistent. I suspect what you want is:
if (dataIn[i].YourName !== null && dataIn[i].YourName !== '' ) {
var modifiedName = dataIn[i].YourName.replace(/ \([\s\S]*?\)/g, '');
dataIn[i].YourName = modifiedName;
}

discord.js embeds: UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body embed.fields[0].value: Must be 1024 or fewer in length

I am creating a discord bot that will take data from a website, and display it in an embed.
I stored the data in an array called boxArr. Then I iterate over it, store the data temporarly, and assign it to the correct embed's fields' properties (namely title and value).
It works fine for some pages, but not for others. Whenever if fails, I get an
[UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body embed.fields[0].value: Must be 1024 or fewer in length.] warning.
However the embed's values never exceeds 1024 characters in length, so I am baffled as to why I am getting this warning.
Here is my code:
//Create the embed
var exampleEmbed = new Discord.MessageEmbed()
.setColor('#2D2D2D')
.setTitle(str)
.setURL('/*page link here*/'+str)
.setThumbnail(th)
.addField('‌‌', def + `[Read More...](/*page link here*/${str})`);
//Variable to hold the decision if titles are even or odd
var toOdd = true;
for(i = 0; (boxArr[i] != undefined || boxArr[i] != null); i++) {
if(boxArr[i] === '' || boxArr[i].startsWith('"')) {
if(isOdd(i) === 1) { //If boxArr[i] is nothing and i is odd, titles' location is when i is even
toOdd = false;
continue;
} else { //If boxArr[i] is nothing and i is even, titles' location is when i is odd
toOdd = true;
continue;
}
}
if(toOdd) {
if(isOdd(i) === 1) {
title = boxArr[i]; //Assign title its value
i++; //Increment i
val = boxArr[i];
if(val === undefined || title === undefined) { //Check if one of the two is undefined. If yes then break out without tampering with the embed.
break;
}
Embed.addFields({name: title, value: val, inline: true});
if(boxArr[i+1] === undefined) { //This is unnecessary but I added it nevertheless
break;
}
continue;
}
} else if(!toOdd) { //Similar to if toOdd === true
if(isOdd(i) != 1) {
title = boxArr[i];
i++;
console.log('\n\nVALUE: '+ boxArr[i]);
val = boxArr[i];
if(val === undefined || title === undefined) {
break;
}
Embed.addFields({name: title, value: val, inline: true});
if(boxArr[i+1] === undefined) {
break;
}
continue;
}
}
}
message.channel.send(Embed); //send the embed
Any help is appreciated.
So I found the problem.
Apparently the problem is that the embed itself has over 1024 characters.
Removing [Read More...](/*page link here*/${str}) from .addField('‌‌', def + [Read More...](/*page link here*/${str})); solved the problem.
EDIT: Another fix is to limit str to 500 characters.

Firebase: Query.on failed: Was called with 1 argument. Expects at least 2

The error is in the title.
The app I´m building is based on React and Firebase.
I am trying to use promises.
Here is my code:
gamesRef.on('value').then(function(snapshot){
// find all empty games
var gamesToRemove = [];
snapshot.forEach(game => {
if(game.val().player1 == ""
&& game.val().player2 == ""
&& game.val().player3 == ""
&& game.val().player4 == ""){
gamesToRemove.push(game.key());
}
});
return gamesToRemove;
}).then(function(gamesToRemove){
// remove all empty games
for(var index in gamesToRemove){
gamesRef.child(gamesToRemove[index]).remove();
}
}, function(error){
console.log(error);
});
I found this question on SO that addressed the same issue. The solution was that the Firebase version needs to be at least 2.4 to use promises. I used an older version, but after upgrading to 2.4.2, i still get the same error. What should I do?
Edit: Code after fix. Get error "gamesRef.on(...).then is not a function".
gamesRef.on('value', function(snapshot){
// find all empty games
var gamesToRemove = [];
snapshot.forEach(game => {
if(game.val().player1 == ""
&& game.val().player2 == ""
&& game.val().player3 == ""
&& game.val().player4 == ""){
gamesToRemove.push(game.key());
console.log("denna borde raderas: " + game.key());
}
});
return gamesToRemove;
}).then(function(gamesToRemove){
// remove all empty games
for(var index in gamesToRemove){
gamesRef.child(gamesToRemove[index]).remove();
}
});
You have wrong mindset about on+then,
on takes 2 arguments: the name for event, and callback, callback is just plain function which takes event as argument:
gamesRef.on('value', function(snapshot){
// find all empty games
var gamesToRemove = [];
snapshot.forEach(game => {
if(game.val().player1 == ""
&& game.val().player2 == ""
&& game.val().player3 == ""
&& game.val().player4 == ""){
gamesToRemove.push(game.key());
}
});
return gamesToRemove;
})
and then, you can use your then :D
While many function in the Firebase JavaScript client return a promise, on() is not one of them.
The reason for this is that on() will typically deliver a value multiple times, while the contract of a promise is that then() will resolve at most once.
If you only care about getting the value of the data once, you can use once() and a promise:
gamesRef.once('value').then(function(snapshot){
// find all empty games
var gamesToRemove = [];
snapshot.forEach(game => {
if(game.val().player1 == ""
&& game.val().player2 == ""
&& game.val().player3 == ""
&& game.val().player4 == ""){
gamesToRemove.push(game.key());
}
});
return gamesToRemove;
}).then(function(gamesToRemove){
// remove all empty games
for(var index in gamesToRemove){
gamesRef.child(gamesToRemove[index]).remove();
}
}.catch(function(error){
console.log(error);
});

Meteor detecting existence of field in collection

Pseudo code below. My result collection of products has an optional subarray of images. What I'm trying to do is check if images exists for a product before trying to access an image.href to use as an image source. In the case where images does NOT exist it breaks every time. Alternately I've tried typeof 'undefined' and that didn't work either.
if (this.products) {
//return "<i class='fa fa-gift'></i>"
console.log("has products");
if (this.products[0].images) { <--- breaks
console.log("item 0 has images");
}
if (this.products.images) { <--- breaks
console.log("has images");
}
} else {
console.log("don't have products");
}
EDIT / UPDATE
Ultimately I think Patrick Lewis supplied the best answer for this - using a hybrid ternary operator. Goes like:
myVar = object && object.name || "foo"
above would assign myVar the name value if the object exists and it has a name, or... it will assign static "foo".
Probably this.products is an empty array. Try:
if (this.products && this.products.length) {
var images = this.products[0].images;
if (images && images.length) {
console.log("item 0 has images");
} else {
console.log("item 0 does not have images");
}
} else {
console.log("don't have products");
}
this.products is your collection or the result of a query like MyColl.find() ?
if this is the result of a query you could do this :
if (typeof this.products == "object") {
if (typeof this.products.images == "object") { // if images is a property of products and images is an array
// od what you want here
}
}

Access js array in another js file

I fill my array in the checklistRequest.js and I want to access it in my Termine_1s.html file which contains js code. I can access it but when I want to iterate through it, it gives me only single digits instead of the strings.
How can I solve this?
checklistRequest.js
//Calls the checkbox values
function alertFunction()
{
//Retrieve the object from storage
var retrievedObject = localStorage.getItem('checkboxArray');
console.log('retrievedObject: ', JSON.parse(retrievedObject));
return retrievedObject;
}
Termine_1s.html
//Checks if title was checked already
var checklistRequest = alertFunction();
var titleAccepted = true;
for (var a = 0; a < checklistRequest.length; a++)//Iterates through whole array
{
if(title != checklistRequest[i] && titleAccepted == true)//Stops if false
{
titleAccepted = true;
}
else
{
titleAccepted = false;
}
}
you need to parse the object at some point.
Try:
return JSON.parse(retrievedObject);

Categories

Resources