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
}
}
Related
I have an array of playlists. A playlist has many posts.
I am trying to determine whether the selected playlist already contains the post I choose to add.
Currently, I'm getting "Already added" if any playlist in the playlists array contains that post.
I only want to add posts to playlists that DO NOT already contain that post.
Basically, I want to still be able to add a post to a playlist even if another playlist contains that post.
const confirmAdd = (selectedPlaylist, selectedPost) => {
for(var i = 0; i < playlists.length; i++) {
if (playlists[i].posts.length > 0) {
if (playlists[i].posts.some(post => post.id != selectedPost.id)) {
console.log("Success")
} else {
console.log("Already added")
}
break
} else {
console.log("Success")
break
}
}
}
The playlist parameter to the confirmAdd() function should be playlists since that is what you are using within the function
you can use "indexOf"
let myArray = ["hello", "this", "is", "array"];
if(myArray.indexOf("hello") > -1){
console.log("Hello is available")
}else{
console.log("not available")
}
The indexOf() method returns the position of the first occurrence of a specified value in a string.
This method returns -1 if the value to search for never occurs.
-w3schools
Javascript has a lot of great functions baked in to help with array manipulation.
For this task, you can use .includes() to check an array for duplicate data.
if(playlist.includes(post)){
...do the thing
} else {
...do the other thing
}
So, I guess you have information about the selected playlist and if it's an object let's refer it by an object called selectedPlaylist. In that case your code should be something like below
function confirmAddFn(selectedPlaylist = {}, reqpost = {}) {
//Here Selected Play list is the reference object of the selection
//searching for the post
let filteredPost = selectedPlaylist.posts.items.filter(post => post.id == reqpost.id);
//if there is a post log already exsist
if (filteredPost.length > 0) {
console.log("Already Exsist");
}
else {
//else add to the ref ob
selectedPlaylist.posts.items.push(reqpost);
}
}
Now, in case you don't have the selected object and just have the index of the selected post. the below code should help
function confirmAddFn(playList = [], reqpost = {}, selectedPlayListIndex = -1) {
//Here Selected Play list is the reference object of the selection
let selectedPlaylist = playList[selectedPlayListIndex];
//searching for the post
let filteredPost = selectedPlaylist.posts.items.filter(post => post.id == reqpost.id);
//if there is a post log already exsist
if (filteredPost.length > 0) {
console.log("Already Exsist");
}
else {
//else add to the ref ob
selectedPlaylist.posts.items.push(reqpost);
}
}
I'm doing filtering on a data displayed in a view which is working correctly. I've placed a filter bar at the top of the screen where a user can filter the records. What I want to achieve is when the variable the user enters is not found in the records a function should be called
filterProducts(ev) {
this.productService.list = this.reOrderList;
const val = ev.target.value;
if (val && val.trim() !== '') {
this.productService.list = this.reOrderList.filter((item) => {
return (item.name.toLowerCase().indexOf(val.toLowerCase()) > -1);
});
} else {
// value doesn't exist console.log('call another function')
}
}
Check if any items are left in the array after the filter is complete:
if (this.productService.list.length) {
// The user's query was found in the array
} else {
// The user's query was not found in the array
}
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
here I'm pushing product_detail to an empty array product. At first I'm checking if the array is empty, If so the json data is pushed into the array and updated with session. If not I want to verify if the there exists an object with the id, if so it wont push it. but the condition is not becoming true. Dont know what I'm missing or I'm putting the condition wrongly
var product_details = {
product_id: product._id,
user_id: user_id,
};
if (product.length !== 0) {
if (req.session.product.forEach(function(data) {
(data.product_id == req.params._id)
})) {
return res.send("product already present ");
}
product.push(product_detail);
req.session.product = product;
return res.send(req.session.product);
}
product.push(product_detail);
req.session.product = product;
console.log(req.session);
return res.send(req.session.product);
});
Simply change your nested condition to:
var arrayTrue = true;
req.session.product.forEach(function(data) {
if(data.product_id == req.params._id){
arrayTrue = false;
}
});
if(arrayTrue){
// Doesn't exist...
}
else{
return res.send("Product already present");
}
i've written 3 little function that save, load or delete a single entry in an array saved with jstorage.
The two first functions works perfectly .
But the one that delete a single entry systematically delete the whole array or doesn't save it.
Could someone point me the problem, which is probably in my code ?
function local_single_delete(poi_id){
if ($.jStorage.storageAvailable()== true) { // if local storage is available
loctab = $.jStorage.get("poi_ids"); // load saved data
if (loctab == null) { // if no saved data => null array
loctab = new Array();
console.log('loctab is null');
}
for (local_i = 0; i < loctab.length; local_i++ ){ // for each saved data , looking for one one in particular
if (loctab[local_i]['id_poi'] === poi_id) { // if found
loctab[local_i]= loctab[loctab.length-1]; // the one becomes the last entry value,
loctab.length =loctab.length -1; // then we truncate the array for one position
break; // and we leave the for
}
}
$.jStorage.set("poi_ids",loctab); // write data
$.jStorage.flush(); // clear cache
}
else {
console.log('on a pas de stockage local');
}
}
Solution
You delete all data when you flush ... so just don't do it! You also had an non declared i variable.
function local_single_delete(poi_id){
if ($.jStorage.storageAvailable() === true) {
loctab = $.jStorage.get("poi_ids");
if (loctab === null) {
loctab = [];
console.log('loctab is null');
}
for (local_i = 0; local_i < loctab.length; local_i++ ){
if (loctab[local_i].id_poi === poi_id) {
loctab[local_i]= loctab[loctab.length-1];
loctab.length =loctab.length - 1;
break;
}
}
$.jStorage.set("poi_ids",loctab);
}
else {
console.log('on a pas de stockage local');
}
}