I currently have a product page where user can add items to a basket. Once the item is added its stores the product ID in the local storage. I would like to be able to then add all the items they selected to the cart page, displaying the price, name and image. I'm not really sure how to go about this, please could you help me out.
data structure with each product having a unique ID:
{
"products": [{
"id": "0",
"name": "Logitech G910 Orion Spectrum RGB Mechanical Gaming Keyboard - UK-Layout",
"price": "119.99",
"category": "0",
"description": "Logitech 920-008017 G910 Orion Spectrum RGB Mechanical Gaming Keyboard - Black.",
"images": [{
"id": "0",
"src": "images/00.jpg"
},
{
"id": "1",
"src": "images/01.jpg"
},
{
"id": "2",
"src": "images/02.jpg"
}
]
},
Code that adds an item to a basket:
$('#myTable').on('click', '.cartbutton', function() {
var row = $(this).parents('tr');
console.log(row.attr('id'), row.data('price'));
added.push(row.attr('id'));
localStorage.setItem("cartItems", JSON.stringify(added));
var storeddata=localStorage.getItem("cartItems");
console.log(storeddata);
})
A example of the resulting array:
["0", "0", "0", "1", "1"]
You can iterate the array when you need to list the products like
var products = //Your Product Array
for(var i in storeddata)
{
var id = storeddata[i];
var obj = products.filter(function ( obj ) {
return obj.id === id;
})[0];
console.log(obj);//This will be you product
}
Related
I would like to match the "title" and "thumbnail" values from one json response array to the values in another response array and show them in an html list. Essentially I'm matching a multidimensional array by regEx to another array and then I'm trying to display the content in a list like the one at the bottom. Any help is appreciated.
Here is the 1st Array
jsonArray = [
[{
"position": "1",
"title": "player 1",
"thumbnail": "www.picuture.com/jpeg"
}, {
"position": "2",
"title": "player 1",
"thumbnail": "www.picuture2.com/jpeg"
}],
[{
"position": "1",
"title": "player 2",
"thumbnail": "www.picuture.com/jpeg"
}, {
"position": "2",
"title": "player 2",
"thumbnail": "www.picuture2.com/jpeg"
}],
[{
"position": "1",
"title": "player 3",
"thumbnail": "www.picuture1.com/jpeg"
}, {
"position": "2",
"title": "player 3",
"thumbnail": "www.picuture2.com/jpeg"
}]
]
Below is the the second array it needs to match to
array2 = ["player1_details", "player2_details", "player3_details"]
I would like to have a html list with the title and image values from the jsonArray and the player details from array2.
example:
<ul>
<li>player 1 </li><li>www.picuture1.com/jpeg" </li><li>player1_details </li>
<li>player 2 </li><li>www.picuture2.com/jpeg" </li><li>player2_details </li>
<li>player 3 </li><li>www.picuture3.com/jpeg" </li><li>player3_details </li>
</ul>
So you can do it like this to get player details from position 1 as discussed in comments, its one of the many ways, I have defined a class with required attributes and pushed class object into a list. After this you can use this list to show the details however you want
class reqInformation {
constructor(title, thumbnail, details) {
this.title = title;
this.thumbnail = thumbnail;
this.details = details;
}
}
p = new reqInformation("titletest","thumbnailtest","detailstest");
var finalList=[]
var loopCount = 0;
const itemPos = 1;
Object.keys(jsonArray).forEach(function(key) {
var matchText = jsonArray[key][itemPos]['title'].replace("player ", "");
if(array2[loopCount].includes(matchText)){
var p = new reqInformation(
jsonArray[key][itemPos]['title'],
jsonArray[key][itemPos]['thumbnail'],
array2[loopCount]);
}
finalList.push(p)
loopCount++
});
console.log(finalList)
change itemPos to 0 if you want object at position 0
I'm trying to create DOM elements for an Ingredient filter bar, based on JSON file objects.
The problem is that the same ingredient can appear in several objects, and in that case it should only create the dom element once, not for each time the ingredient occures.
I've tried with childNode, value, innerHTML and !=== but can't figure out the solution. It either creates no element at all, or all of them with duplicates.
Any ideas?
Here is a codePen to help : https://codepen.io/enukeron/pen/eYdgyzx
I also tried with an array to keep track of seen values at this codepen :
https://codepen.io/enukeron/pen/ExgZoLa
JS:
const ingredientDropdown = document.getElementById('ingredientDropdown');
for(var j = 0; j < IngredientList.length; j++) {
if (ingredientDropdown.children.textContent !== IngredientList[j].ingredient) {
var ingredientSearchItems = document.createElement("p");
ingredientSearchItems.textContent = IngredientList[j].ingredient;
ingredientDropdown.appendChild(ingredientSearchItems);
}
}
The JSON file has this format :
{
"id": 49,
"name": "Tropical smoothie",
"servings": 4,
"ingredients": [
{
"ingredient": "Bananas",
"quantity": 2
},
{
"ingredient": "Kiwis",
"quantity": 3
},
{
"ingredient": "Mango",
"quantity": 1
},
{
"ingredient": "Pineapple",
"quantity": 4,
"unit":"slices"
},
{
"ingredient": "Honey",
"quantity": 2,
"unit": "tablespoons"
}
],
"time": 0,
"description":"Chop the fruit. Liquefy in the blender. Chill. Serve",
"appliance": "Blender",
"ustensils":["couteau", "verres"]
}, etc.....
The actual result is :
The Expected Result is :
You could create a function like the following:
function filterIngredients(recipes){
let return_arr = [];
recipes.forEach((recipe, index, array)=>{
let ingredients = recipe["ingredients"];
ingredients.forEach((ingredient, index, inner_array)=>{
if(!return_arr.includes(ingredient["ingredient"])){
return_arr.push(ingredient["ingredient"]);
}
});
});
return return_arr;
}
And then call the function as follows:
var ingredients = filterIngredients(recipes);
You can then loop through ingredients and display them in the div as you want (hoping this is what you wanted in the first place).
Here is a link to my pen where I implemented it:
https://codepen.io/AnirudhMS/pen/MWjJQgg?editors=1010
How to pass array of values as filter in angularjs
My scenario
cuisines json: ["food", "Alcohol","Thai"]
catorigeres json :["home", "office","school"]
values with cuisines and categories :
[{
"_id": "1",
"businessTypeName": "Pizza Hut",
"cus_name": ["food","Thai"],
"cat_name": ["home", "school"],
}, {
"_id": "2",
"businessTypeName": "Chicken Hut",
"cus_name":["Alcohol","Thai"],
"cat_name": ["office", "home"],
}, {
"_id": "3",
"businessTypeName": "Fish Hut",
"bussiness_url": "/dist/images/loop_image_sample_3.png",
"cus_name": ["Thai"],
"cat_name": ["office", "school"],
}]
cuisines and categories are of in checkbox if i click anyone it will append the array of values to {{selected}}
my question is how to filter values in {{selected}} to listing_loop div
my plunker demo
I don't think you can do that in html alone.
You can add a filtering function to the scope:
$scope.customFilter = function(value, index, array) {
// make sure `value.id` is a string
return ["food","Thai","Alcohol"].indexOf(value.id);
}
and using like this in HTML
<div ng-repeat="set in get | filter:customFilter"></div>
I'm using Firebase 2.4.2. I have a database as follows:
"items": {
"item1": {
"details": {
"name": "item 1",
"rate": 5
},
"item2": {
"details": {
"name": "item 2",
"rate": "4"
}
}
"item3": {
"details": {
"name": "item 3",
"rate": "6"
}
}
}
I have thousands of items and don't want to load them all in a table. Rather, I'd like to load the top10 along with the item that user has clicked on. So, if you are in the page: /items/details/item2, I'd like you see the top10 items in the database (based on their rates) and the item2 in a table. I'd also like to show the index of item2 in the ordered list.
ind id rate
1 item56 100
2 item33 98
...
143 item2 13
What we do normally -if the bandwidth is not issue- is to retrieve all data as follows (e.g. using AngularFire)
var ref = fbutil.ref('items').orderByChild('details/rate');
return $firebaseArray(ref);
However, I'd like to order them, retrieve the top10, and then retrieve the item2 (in this case) and its index (143) based on its rate.
How would I do that?
// For getting top 10
var ref = fbutil.ref('items').orderByChild('details/rate').limitToFirst(10);
return $firebaseArray(ref);
// For getting single
var ref = fbutil.ref('items').orderByChild('details/rate').equalTo(13);
var singleItem = $firebaseObject(ref);
Checkout the following link to see what methods firebase.database.Reference class supports.
https://firebase.google.com/docs/reference/js/firebase.database.Reference
I'm having trouble finding a solution that will help me loop through a bunch of elements and putting the chosen values into a table. I've been able to withdraw some values but the method isn't dynamic.
Here is an example:
var Table = {
"credit": {
"link": "site link",
"logoUrl": "logo url",
"message": "message"
},
"groups": [
{
"labels": [
{
"name": "Western Conference",
"type": "conference"
},
{
"name": "Central Division",
"type": "division"
}
],
"standings": [
{
"stats": [
{
"name": "gp",
"value": 20
},
{
"name": "w",
"value": 17
},
{
"name": "l",
"value": 0
},
{
"name": "gf",
"value": 64
},
{
"name": "ga",
"value": 37
},
{
"name": "gd",
"value": 27
},
{
"name": "pts",
"value": 37
}
],
"team": {
"id": 12345,
"link": "team link",
"name": "team name",
"shortName": "team"
}
},
This is the structure of the elements. So far I've used this:
document.getElementById("sGamesPlayed").innerHTML=Table.groups[0].standings[0].stats[0].value;
to withdraw values. However there are more teams, stats and divisions so I would need some kind of loop to go through the elements and put the into a dynamic table.
I would consider you to look at http://underscorejs.org/.
it provides a bunch of utility functions that could help you,
for example, _.each() helps you loop through JSON properties.
for the sample objects you've given (after completing the missing brackets at the end),
_.each(Table.groups[0].standings[0].stats, function(stats){
console.log(stats['name']+","+stats['value'])
})
gives me:
gp,20
w,17
l,0
gf,64
ga,37
gd,27
pts,37
how it works is that you provide the object you want as the first argument and the function that you give as the second argument will be called with each element of the first argument (Assuming it is a list).
I would also urge you to look at underscore templating that you can use to render your table where i put the console.log :
http://net.tutsplus.com/tutorials/javascript-ajax/getting-cozy-with-underscore-js/
http://scriptble.com/2011/01/28/underscore-js-templates/
I guess your question is about filtering the values of the array standings. In order to do that you can use the jQuery grep function (if you want to use jQuery).
For example you can write:
var arr = $.grep(Table.groups[0].standings[0].stats, function(d){return d.value>25})
Which will give
arr = [{"name": "gf","value": 64}, {"name": "ga", "value": 37},{"name": "gd", "value": 27},{"name": "pts", "value": 37}]
If this is not what you meant, can you please create a jsFiddle with a sample of what you want?
Depending on what you want to do with the results, you can go over the object using a scheme like:
var groups, standings, stats, value;
groups = Table.groups;
// Do stuff with groups
for (var i=0, iLen=groups.length; i<iLen; i++) {
standings = groups[i].standings;
// Do stuff with standings
for (var j=0, jLen=standings.length; j<jLen; j++) {
stats = standings[j];
// Do stuff with stats
for (var k=0, kLen=stats.length; k<kLen; k++) {
value = stats[k].value;
// Do stuff with value
}
}
}
Of course I have no idea what the data is for, what the overall structure is or how you want to present it. But if you have deeply nested data, all you can do is dig into it. You might be able to write a recursive function, but it might also become very difficult to maintain if the data structure is complex.