I have a cart on my website and I need to let users easily change the quantity of items they have in their cart at a moment.
Here is the javascript code I have so far:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
var items = [];
$(".item").each(function () {
var productKey = $(this).find("input[type='hidden']").val();
var productQuantity = $(this).find("input[type='text']").val();
items.addKey(productKey, productQuantity); ?
});
// 1. Grab the values of each ammount input and it's productId.
// 2. Send this dictionary of key pairs to a JSON action method.
// 3. If results are OK, reload this page.
});
</script>
The comments I wrote are just guidelines for me on how to proceed.
Is there a way to add a key/pair element to an array of sorts? I just need it to have a key and value. Nothing fancy.
I wrote in an addKey() method just for illustrative purposes to show what I want to accomplish.
items[productKey] = productQuantity;
In JavaScript, Arrays are Objects (typeof(new Array)==='object'), and Objects can have properties which can be get/set using dot- or bracket- syntax:
var a = [1,2,3];
JSON.stringify(a); // => "[1,2,3]"
a.foo = 'Foo';
a.foo; // => 'Foo'
a['foo']; // => 'Foo'
JSON.stringify(a); // => "[1,2,3]"
So in your case, you can simply the productQuantity value to the productKey attribute of the item array as such:
items[productKey] = productQuantity;
items[productKey]; // => productQuantity
You can add anonymous objects to the items array like:
items.push({
key: productKey,
quantity: productQuantity
});
Then access them later as items[0].key or items[0].quantity.
Also you can use JQuery.data method and like that you can also get rid of those hidden.
Related
I am trying to retrieve an arrray from local storage, append a new array with the same keys, then stick it back into storage. I can't seem to get it to work however, I've tried turning my arrays into object, and objects into arrays (I'm new to programming so I'm not sure what the best way is.) I've also tried using the spread operator, object.entries(), object.assign() and a few other nonsensical options.
EDIT:
Saved to storage are the user input values:
"[[["name","bob ross"],["about","Painter"]]]"
I want the user to be able to add "Bilbo Baggins" for name, and "Hobbit" for about, then the storage should look like:
"[[["name","bob ross"],["about","Painter"]]], [[["name","Bilbo Baggins"],["about","Hobbit"]]]"
Any help would be greatly appreciated! Here's my code:
//============= Allows writing to LocalStorage without overwrite ==========================
submitbtn.addEventListener('click', function () {
const oldInfo = JSON.parse(localStorage.getItem('data')); // Retrieves info from storage to make it writeable
console.log('old Info: ', oldInfo); // Shows user what's currently saved in oldInfo
const newInfo = {};
newInfo.name = name.value; // Name and about are user input values
newInfo.about = about.value;
let array = Object.entries(newInfo); // Turns newInfo into an array
console.log('new info: ', newInfo);
oldInfo.push(array); // Appends newInfo to oldInfo without overwriting oldInfo data
console.log(oldInfo);
localStorage.setItem('data', JSON.stringify(oldInfo)); // Saves newly updated array to localStorage
});
I advise you to keep an object format, as you seems to only need to update properties, and not store.
That way, you can simply update your store by using your oldInfo object and using spread operator to create a new object from it (and get rid of conversion):
Let's say you put this in your localStorage (stringified):
const initialInfo = {
name: '',
about: ''
};
Then you can simply do
const oldInfo = JSON.parse(localStorage.getItem('data'));
localStorage.setItem(
'data',
JSON.stringify({ ...oldInfo, name: name.value, about: about.value })
);
This ... are syntaxic sugar for Object.assign, and to my mind, helps a lot to read instruction.
Here it means that you are 'cloning' the oldInfo object, and assigning new values to listed properties placed behind it.
EDIT:
After question editing; if you want to store multiple objects within an array, you should go with array spread operator. Like so:
const oldInfo = JSON.parse(localStorage.getItem('data'));
// oldInfo = [{ name: 'example', about: 'test' }];
const yourNewObject = {
value: name.value,
about: about.value
};
localStorage.setItem(
'data',
JSON.stringify([ ...oldInfo, yourNewObject ])
);
This way you will add an object to your array
I've cleaned up the code a little.
Your code should work, except that is was missing some error handling for the first load.
// Mock data
const name = { value: 'Foo name' };
const about = { value: 'Bar about' };
const submitbtn = document.getElementById('submit');
// Fake localStorage to make it work in the snippet
mockLocalStorage = {
getItem: (key) => this[key],
setItem: (key, value) => this[key] = value
};
submitbtn.addEventListener('click', function() {
// Make sure we get -something- back in case this is the first time we're accessing the storage.
const oldInfo = JSON.parse(mockLocalStorage.getItem('data') || '[]');
console.log('Before', oldInfo);
// The creation of the new object can be done in 1 step.
const array = Object.entries({
name: name.value,
about: about.value
});
oldInfo.push(array); // Appends newInfo to oldInfo without overwriting oldInfo data
console.log('After', oldInfo);
mockLocalStorage.setItem('data', JSON.stringify(oldInfo));
});
<button id="submit" type="button">Submit!</button>
Json Array Object
Through Ajax I will get dynamic data which is not constant or similar data based on query data will change. But I want to display charts so I used chartjs where I need to pass array data. So I tried below code but whenever data changes that code will break.
I cannot paste complete JSON file so after parsing it looks like this
[{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
You can use Object.keys and specify the position number to get that value
var valueOne =[];
var valueTwo = [];
jsonData.forEach(function(e){
valueOne.push(e[Object.keys(e)[1]]);
valueTwo.push(e[Object.keys(e)[2]]);
})
It seems like what you're trying to do is conditionally populate an array based the data you are receiving. One solution might be for you to use a variable who's value is based on whether the value or price property exist on the object. For example, in your forEach loop:
const valueOne = [];
jsonData.forEach((e) => {
const val = typeof e.value !== undefined ? e.value : e.average;
valueOne.push(val);
})
In your jsonData.forEach loop you can test existence of element by using something like:
if (e['volume']===undefined) {
valueone.push(e.price);
} else {
valueone.push(e.volume);
}
And similar for valuetwo...
You could create an object with the keys of your first array element, and values corresponding to the arrays you are after:
var data = [{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
var splitArrays = Object.keys(data[0]).reduce((o, e) => {
o[e] = data.map(el => el[e]);
return o;
}, {});
// show the whole object
console.log(splitArrays);
// show the individual arrays
console.log("brand");
console.log(splitArrays.brand);
console.log("volume");
console.log(splitArrays.volume);
// etc
I'm trying to match and group objects, based on a property on each object, and put them in their own array that I can use to sort later for some selection criteria. The sort method isn't an option for me, because I need to sort for 4 different values of the property.
How can I dynamically create separate arrays for the objects who have a matching property?
For example, I can do this if I know that the form.RatingNumber will be 1, 2, 3, or 4:
var ratingNumOne = [],
ratingNumTwo,
ratingNumThree,
ratingNumFour;
forms.forEach(function(form) {
if (form.RatingNumber === 1){
ratingNumOne.push(form);
} else if (form.RatingNumber === 2){
ratingNumTwo.push(form)
} //and so on...
});
The problem is that the form.RatingNumber property could be any number, so hard-coding 1,2,3,4 will not work.
How can I group the forms dynamically, by each RatingNumber?
try to use reduce function, something like this:
forms.reduce((result, form) => {
result[form.RatingNumber] = result[form.RatingNumber] || []
result[form.RatingNumber].push(form)
}
,{})
the result would be object, with each of the keys is the rating number and the values is the forms with this rating number.
that would be dynamic for any count of rating number
You could use an object and take form.RatingNumber as key.
If you have zero based values without gaps, you could use an array instead of an object.
var ratingNumOne = [],
ratingNumTwo = [],
ratingNumThree = [],
ratingNumFour = [],
ratings = { 1: ratingNumOne, 2: ratingNumTwo, 3: ratingNumThree, 4: ratingNumFour };
// usage
ratings[form.RatingNumber].push(form);
try this its a work arround:
forms.forEach(form => {
if (!window['ratingNumber' + form.RatingNumber]) window['ratingNumber' + form.RatingNumber] = [];
window['ratingNumber' + form.RatingNumber].push(form);
});
this will create the variables automaticly. In the end it will look like this:
ratingNumber1 = [form, form, form];
ratingNumber2 = [form, form];
ratingNumber100 = [form];
but to notice ratingNumber3 (for example) could also be undefined.
Just to have it said, your solution makes no sense but this version works at least.
It does not matter what numbers you are getting with RatingNumber, just use it as index. The result will be an object with the RatingNumber as indexes and an array of object that have that RatingNumber as value.
//example input
var forms = [{RatingNumber:5 }, {RatingNumber:6}, {RatingNumber:78}, {RatingNumber:6}];
var results = {};
$.each(forms, function(i, form){
if(!results[form.RatingNumber])
results[form.RatingNumber]=[];
results[form.RatingNumber].push(form);
});
console.log(results);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HIH
// Example input data
let forms = [{RatingNumber: 1}, {RatingNumber: 4}, {RatingNumber: 2}, {RatingNumber: 1}],
result = [];
forms.forEach(form => {
result[form.RatingNumber]
? result[form.RatingNumber].push(form)
: result[form.RatingNumber] = [form];
});
// Now `result` have all information. Next can do something else..
let getResult = index => {
let res = result[index] || [];
// Write your code here. For example VVVVV
console.log(`Rating ${index}: ${res.length} count`)
console.log(res)
}
getResult(1)
getResult(2)
getResult(3)
getResult(4)
Try to create an object with the "RatingNumber" as property:
rating = {};
forms.forEach(function(form) {
if( !rating[form.RatingNumber] ){
rating[form.RatingNumber] = []
}
rating[form.RatingNumber].push( form )
})
I'm creating a very simplified version of a drag and drop shopping cart with jqueryui.
My issue is regarding adding data(id, name, price) to an array.
I tried several methodes of adding the data (also an array) to the main container(array). But I keep getting this error: Uncaught TypeError: undefined is not a function
var data = [];
function addproduct(id,name,price){
//var d = [id,name,price];
data[id]["name"] = name;
data[id]["price"] = price;
data[id]["count"] = data[id]["count"]+1;
console.log(data);
}
the addproduct() function can be called by pressing a button
It is not entirely clear to me what type of data structure you want to end up with after you've added a number of items to the cart. So, this answer is a guess based on what it looks like you're trying to do in your question, but if you show a Javascript literal for what you want the actual structure to look like after there are several items in the cart, we can be sure we make the best recommendation.
You have to initialize a javascript object or array before you can use it. The usual way to do that is to check if it exists and if it does not, then initialize it before assigning to it. And, since you're keeping a count, you also will want to initialize the count.
var data = [];
function addproduct(id,name,price){
if (!data[id]) {
// initialize object and count
data[id] = {count: 0};
}
data[id]["name"] = name;
data[id]["price"] = price;
++data[id]["count"];
console.log(data);
}
And FYI, arrays are used for numeric indexes. If you're using property names like "name" and "price" to access properties, you should use an object instead of an array.
And, I would suggest that you use the dot syntax for known property strings:
var data = [];
function addproduct(id,name,price){
if (!data[id]) {
// initialize object and count
data[id] = {count: 0};
}
data[id].name = name;
data[id].price = price;
++data[id].count;
console.log(data);
}
It looks like what you want is an array of objects, although I would need a more detailed description of your problem to be clear.
var data = []
function addproduct(id, name, price)
{
data.push({'id': id, 'name':name, 'price': price, 'count': ++count});
console.log(data);
}
I'm trying to put together a web form to mark an indeterminate number of employees as either present or absent. The page itself contains an arbitrary number of divs of the form:
<div class="employee" empID="9" presence="0">
The divs themselves contain the options, with 'presence' being changed to 1 or 2 using jQuery depending on the option selected.
When the 'submit' button is pressed, I'd like to convert this data into a parsable array of pairs of 'empID' and 'presence'. I've tried doing this with jQuery as follows:
$('.cic-button').click(function(){
var submitData = {employees:[]};
$('firedrill-employee').each(function(){
submitData.push({
employeeID: $(this).attr('empID'),
presence: $(this).attr('presence')
});
});
});
However, when this is done, the submitData variable is failing to populate. Any idea why? Am I going about this in the correct manner? Is what I'm trying to do even possible?
Many thanks.
You have a few errors. Make the class that you iterate over the collection of "employee" not "firedrill-employee" and don't forget the dot to indicate it's a class. Reference the employees array withing the submitData object. You can't just push an element into an object.
$('.cic-button').click(function () {
var submitData = {
employees: []
};
$('.employee').each(function () {
submitData.employees.push({
employeeID: $(this).data('empID'),
presence: $(this).data('presence')
});
});
console.log(submitData);
});
Fiddle
Js fiddle
$('.cic-button').click(function () {
var submitData = [];
$('.employee').each(function () {
var self = $(this);
// Create and obj
var obj = new Object(); // {};
obj["employeeID"] = self.attr("empID");
obj["presence"] = self.attr("presence");
//push that object into an array
submitData.push(obj);
console.log(obj);
console.log(submitData);
});
});
You need to specify the employee array as such:
$('.cic-button').click(function(){
var submitData = {employees:[]}; // employees is an array within submitData...
$('.firedrill-employee').each(function(){
submitData.employees.push({ // ...so amend code here to push to the array, not submitData
employeeID: $(this).attr('empID'),
presence: $(this).attr('presence')
});
});
console.log(submitData);
});
See example JSFiddle - http://jsfiddle.net/yng1qb6o/