Javascript matrix array issue - javascript

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);
}

Related

Remove element from named values in javascript

I have the following function, which is called when a google forms is submitted. I'm trying to concatenate all answers into a single array that's gonna be used latter:
function onFormSubmit(e) {
var respostas = e.namedValues;
for(item in respostas){
rp = rp.concat(respostas[item]);
}
}
But I would like to drop the timestamp that comes together with the answers. I can access it with respostas['Timestamp'], but I can't find a way to drop or ignore it. The documentation didn't help much.
var cp = [];
function onSubmitForm(e) {
var respostas = e.namedValues;
for (var name in respostas) {
if (respostas.hasOwnProperty(name) {
if (name !== 'Timestamp') {
cp.push(respostash[name]);
}
}
}
}
This is what I would suggest. Using concat to add an item is overkill, you can just push it. Also is a good practice when you are looping over object properties to make sure that they are its own properties of that object, not inherited from prototype. You can read more about it here
You can check the name of the property before concatenate it with the rest.
If the key item equals Timestamp (the undesired property) just skip the current loop.
for(item in respostas) {
if (item === 'Timestamp') {
continue;
}
rp = rp.concat(respostas[item]);
}
EDIT: Based on comments, OP attests that item in the for..in loop is a integer, but, unless his/her code differs radically from the docs, the variable should hold strings, not numbers.
var respostas = {
'First Name': ['Jane'],
'Timestamp': ['6/7/2015 20:54:13'],
'Last Name': ['Doe']
};
for(item in respostas) {
console.log(item);
}
e.namedValues returns a JSON Object with custom keys.
var jsonObj = e.namesValues;
/* e.namedValues returns data like this...
{
"test1": "testval1",
"test2": "testval2",
"test3": "testval3",
}
*/
for(item in respostas){
Logger.log(item); //Key
Logger.log(respostas[item]); //Value
}
This should let you access the key or value on the items in respostas.
The accepted answer is better as it does more to help the user to fix their exact problem, however, I will leave this here for future users in case they want to understand how to access the variables in the object that Google Apps Scripts returns.

How to fetch values from json array object without using object key name javascript?

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

Dynamic Variable Names with JavaScript - Two arrays?

I'm trying to generate markers for every user in my $.each loop in such a way that I can select each marker using the corresponding userId of a given user.
$.each($.parseJSON(window.usersArray), function (i, user) {
window.userMarkers[user['id']] = L.marker(98.76, 12.34).addTo(map);
console.log(window.userMarkers[user['id']]);
});
EDIT
I get the error:
Cannot set property '3' of undefined, where 3 is the user's ID.
You need to create the object (or array depending on your needs) before you can add anything to it.
window.userMarkers = {};
$.each($.parseJSON(window.usersArray), function (i, user) {
window.userMarkers[user['id']] = L.marker(98.76, 12.34).addTo(map);
console.log(window.userMarkers[user['id']]);
});
Solution: Define the array before setting properties to it! Example:
window.userMarkers = new Array();

Data storage in jquery

I want to store objects in jquery. The objects are 'events' each event has a date, title and some text. They need to be stored like and array (maybe thats what they will be a multi-dimensional array) so I can iterate through them with a counter.
Edit,
I like the stores var as a way to group the info but how do I add multiple items and how do I index them?
var dates = new Array('12th Dec', '14th Jan', '6th May');
var event_title = new Array('My Birthday', 'Going to Beach', 'Holiday');
var event_text = new Array('One Year Older', 'Remember the suntan lotion', 'on the plane to spain');
I need to return by index alert(dates[2], event_title[2], event_text[2]);
you can try:
var store = {};
store = {
dates : dates,
titles: titles,
infotxt: infotxt
};
Then access:
store.dates or store.title or so..
You probably don't want to store separate related info in arrays as you're doing, and then attempt to access those groups by index.
JavaScript has a perfect, native object that allows you to group similar properties. Just use an object literal:
var events = [];
events.push({
data: someData,
title: someTitle,
text: someText
});
Now you have what's referred to oftentimes as a "collection".
You could take it a step further and make each event a "class":
function MyAwesomeEvent(data, title, text) {
this.data = data;
this.title = title;
this.text = text;
}
events.push(new MyAwesomeEvent(someData, someTitle, someText));
That approach is potentially heavy-handed depending on what your specific use-case is, but it's another option.

Creating a key/pair object using jQuery and some inputs

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.

Categories