How would i check to see if the ID exists within the localStorage object key array
i am currenty using this and it does not work
if (favorites.includes(theid)) { alert('You Allready Added this Listing'); }
Also how do i pull the indivdual object array apart into ID , image , title
to make varibles
Thank you
Below is the Full Code
function checkfave (theid) {
// get favorites from local storage or empty array
var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
var theimage = $('#theimage'+theid).attr('src');
var thetitle = $('#thetitle'+theid).text();
if (localStorage.getItem('favorites') != null) {
if (favorites.includes(theid)) { alert('You Allready Added this Listing'); }
}
favorites.push({ID:theid,IMAGE:theimage,TITLE:thetitle});
localStorage.setItem('favorites', JSON.stringify(favorites));
alert('You Just Added Listing '+theid+' To Your Favorites');
//Loop through the Favorites List and display in console (HIDDEN)
console.clear();
for (let i = 0; i < favorites.length; i++) {
console.log('ID= '+favorites[i].ID+' IMAGE='+favorites[i].IMAGE+' TITLE='+favorites[i].TITLE);
}//for loop
}
When you parse json using JSON.parse, a javascript object is created. You can access keys in javascript objects by simply using the bracket notation:
object[key] = value
If a key is not defined in an object, when you request the key you will get undefined. undefined is equivalent to false when evaluating an if clause so you can simply use
if (favorites[theid]) { alert('You Allready Added this Listing'); }
I found a solution after the suggestions
My solution was to check within a for loop using favorites[i].ID == theid
The final code is below. i am very sure it could be done another way, But this works for now.
function checkfave (theid) {
var favorites = JSON.parse(localStorage.getItem('favorites')) || [];
var theimage = $('#theimage'+theid).attr('src');
var thetitle = $('#thetitle'+theid).text();
var added=true;
//Loop through the Favorites List and display in console (HIDDEN)
for (let i = 0; i < favorites.length; i++) {
if ( favorites[i].ID == theid ) { alert('You allready Added Listing '+theid+' To Your Favorites'); var added=false; break; } else {var added=true;}
}//for loop
if (added===true) {
favorites.push({ID:theid,IMAGE:theimage,TITLE:thetitle});
localStorage.setItem('favorites', JSON.stringify(favorites));
alert('You Just Added Listing '+theid+' To Your Favorites');
}
}
Related
Currently i have this code on my api call to add a check property (list) (based on api called data "resRole" and "res") which can be used inside of rowSelection to select all the default checked row.
However, now i have another table which I need to do the same thing. Just that instead of using resRole, now I will use resProject. Which i need to first add a key to, before i add a checkProject in "res".
As such, i updated the check to checkRole and intend to put in an additional checkDept (list) in the getAllUserRole's res.data.
Looking at my code, I do not know where I can implement it. It seems like I have to create it inside of the getDataUserRole() function but that seems too messy. And might cause some async issues.
Below is the code:
async function getDataProject() {
let resProject = await getAllProject();
if (resProject) {
setDataSourceProject(resProject.data);
}
}
async function getDataUserRole() {
let resRole = await getAllRoles();
if (resRole) {
//Add a key to every Role
for (var i = 0; i < resRole.data.length; i++) {
resRole.data[i]["key"] = i;
}
setDataSourceRole(resRole.data);
let res = await getAllUserRole();
if (res) {
console.log("getAllUserRole =", res);
for (var i = 0; i < res.data.length; i++) {
//add "check" to every email in the array
res.data[i]["checkRole"] = [];
//loop through all the roleIds array in each email
for (var j = 0; j < res.data[i].roleIds.length; j++) {
//if roleIds is not empty
if (res.data[i].roleIds.length != 0) {
//loop through all Role from getAllRoles and check if any roleIds match the Role. If match push the key of the Role into check
for (var k = 0; k < resRole.data.length; k++) {
if (res.data[i].roleIds[j] == resRole.data[k].id) {
res.data[i]["checkRole"].push(resRole.data[k].key);
}
}
}
}
}
//If groupChange (groupChange is state for storing value of radio button) is null, return untransformed data
if (!(groupChange)) {
setDataSourceUserRole(res.data);
}
//If groupChange has value, call the function with the state value as a parameter
else {
var treeData = groupData(res.data, groupChange)
setDataSourceUserRole(treeData);
}
}
}
}
Instead of Using it inside getDataUserRole(). Use it inside getAllUserRole(). and once you get your result just add additional data with the role and send it back to one function.
If you want to call it separately so then you to depend it one function on another because due to async it will not work properly
How to grab the contentID and content title add it within an array and have it used in the URL of API 2
if i use the code below for section title and sectionid it is working because it is not in an nested array but for the contentid and contenttitle it is not working as it is in a nested array.
In the API 1 test tab i have:
for (i = 0; i < resultCount; i++) {
var id = jsonData[i].contents[0].contentId;
var modelString = jsonData[i].contents[0].contentTitle;
console.log(id)
console.log(modelString)
if (modelString.includes(“APIAUTOMATIONcontent”) || modelString.includes(“Testcontent”) || modelString.includes("{{POST-NewSlide}}") || modelString.includes(“stringcontent”)) {
hasDelete.push(id);
// (id) - this creates an integer (int)
// "announcementId": id, (creating object)
// "hasDelete": modelString.includes("Delete") || modelString.includes("Test")
// });
} else {
doesntHaveDelete.push(id)
// "announcementId": id
// });
}
}
// Check that each object in response contained keyword and length matches from test
pm.test(Number of Content that has APIAUTOMATIONcontent or Test ready to be deleted = ${hasDelete.length} out of Total ${resultCount} , function() {
console.log(hasDelete);
console.log(doesntHaveDelete);
pm.expect(hasDelete.length);
});
pm.collectionVariables.set(‘deletesections’, JSON.stringify(hasDelete));
Like you're iterating over each section in your response body, you also need to iterate over the contents array, you can do it like below:
for (i = 0; i < resultCount; i++) {
contentCount = jsonData[i].contents.length;
for (j = 0; j < contentCount; j++) {
let content = jsonData[i].contents[j];
console.log(content.contentId);
console.log(content.sectionId);
console.log(content.contentTitle);
console.log(content.pdfLink);
console.log(content.videoLink);
console.log(content.sortOrder);
}
}
im geting data from Db using php at first for building a table , later im geting new json data from socket and updating $scope, what i need is to push values that not exist in $scope.
angular.forEach(event.market, (market ,keym) => {
angular.forEach($scope.users.results, function(value, key) {
if(value.marketId == keym) // keym = new marketId from socket
{
//do nothing
}
else
{
//push(new valuse);
}
});
});
the problem im having is that if a marketId dosent match any keys that i allready have then it pushes the amount of times it didnt match instead of pushing 1 time if it didnt match.
what am i doing wrong?
thanks
Before doing push into some array, check whether marketId dose not match any keys and not present in array as well. So in else you will have to add conditions for marketId check and array check.
From what I understand you want to add in an array, missing objects. I think what you are trying to do can be simply achieved by:
angular.forEach(event.market, (valueM, keyM) => {
let isDuplicate = $scope.users.results.filter(user => /* some validation here */).length > 0;
if(!isDuplicate) {
// push new values
}
})
that solved my issue :
angular.forEach(game.market, (market, keym) => {
var addToArray = true;
for (var i = 0; i < $scope.users.results.length; i++) {
if ($scope.users.results[i].marketId == keym) {
addToArray = false;
}
}
if (addToArray) {
$scope.users.results.push({
marketId: keym,
marketName: market.name
});
}
$scope.users.results.marketName = ' ';
$scope.users.results.marketId = ' ';
});
thanks
I want to delete an object in an array when that object's ID is equal to the ID of the object getting compared. Currently, it only removes the first object in the array
if(this.selectedProducts.length > 0){
for(let x of this.selectedProducts){
if(prod._id === x._id){
this.selectedProducts.splice(x,1); //this is the part where I 'delete' the object
this.appended = false;
}else{
this.appended = true;
}
}
if (this.appended) {
this.selectedProducts.push(prod);
}
}else{
this.selectedProducts.push(prod);
}
this.selectEvent.emit(this.selectedProducts);
}
this.selectedProducts.splice(x,1);
The first parameter to splice must be the index, not the object.
If you're using for...of, you can't get the index easily. So you should use a regular for loop instead. With some additional simplifications, your code would look like this:
for (let i = this.selectedProducts.length - 1; i >= 0; this.selectedProducts.length; i--) {
if (prod._id === this.selectProducts[i]._id) {
this.selectedProducts.splice(i, 1); //this is the part where I 'delete' the object
}
}
this.selectedProducts.push(prod);
It's highly likely that using filter would be better anyway:
this.selectedProducts = this.selectedProducts.filter(x => prod._id !== x._id).concat(prod);
I have a scope called $scope.activities. Inside that scope are multiple objects. Each object has a string called viewed with the value of check or uncheck. I would like to check if the value uncheck is present in the scope.
I've created this, but it doesn't seem to work.
if (activities.indexOf("uncheck") == -1) {
console.log ('uncheck found')
$scope.newActivities = 'newActivities';
} else {
console.log ('no uncheck found')
}
Because in activities I have two objects, one with the uncheck value, and a object without it.
[{"id":2,", "viewed":"check"}, {"id":3,", "viewed":"uncheck"}]
You've got to loop each object and check the property - you can use Array.some
var hasValue = activities.some(function(obj) { return obj.viewed == "unchecked" });
You have to loop over each object in the array and test if the property "viewed" equal to "unchek"
var activities = [{"id":2, "viewed":"check"}, {"id":3, "viewed":"uncheck"}];
var activities2 = [{"id":2, "viewed":"check"}, {"id":3, "viewed":"check"}];
var check = function(data){
var checked = false;
for(var i in data){
if(data[i].hasOwnProperty("viewed") && (data[i]["viewed"]=="uncheck") ){
checked = true ;
}
}
return checked;
} ;
console.log(check(activities));
console.log(check(activities2));