Javascript Containing objects in Arrays - javascript

So I've got this code for creating a dialog box in photoshop which contains 4 panels. It worked fine when I wasn't running it through a loop, but the code was bulky and ugly. now I get an error saying "panel1 is undefined". Can I not put objects in arrays like this?
// create a dialog window, dig.panel = dialog panel
var dig = new Window('dialog', 'Poster Interface - Choose 4 Images', [550, 120, 1150, 800]);
//define variables for panel dimensions
var digX = 100;
var digY = 50;
var digWidth = 510;
var digHeight = 140;
var digUp = 110;
var panels = [
[panel1, panel2, panel3, panel4]
];
var labels = [
[label1, label2, label3, label4]
];
var texts = [
[t1, t2, t3, t4]
];
var buttons = [
[bt1, bt2, bt3, bt4]
];
//create panels for the image components
//first loop for panel dimensions multiply by x
// nested loop for contents using i
for (x = 0; x < 4; x++) {
dig.panels[x] = dig.add('panel', [digX, digY + (digUp * x), digWidth, digHeight + (digUp * x)], 'Image ' + (x + 1) + ':');
for (i = 0; i < 4; i++) {
dig.panels[i].labels[i] = dig.panels[i].add('statictext', [20, 20, 120, 40], 'Choose Image' + (i + 1) + ':');
dig.panels[i].texts[i] = dig.panels[i].add('edittext', [125, 20, 325, 40], 'image' + (i + 1) + '.jpg');
dig.panels[i].buttons[i] = dig.panels[i].add('button', [330, 20, 380, 40], 'Open');
}
}
This is wrecking my head. Any advice would be appreciated

To create an array of variables in javascript:
var var1 = "value";
var var2 = "value";
var array = [var1,var2];
You are creating an array, with an array inside it, with variables inside the inner array.
var panels = [
[panel1, panel2, panel3, panel4]
];
You have not displayed to us that those variables have been defined.
Here is a fiddle:
https://jsfiddle.net/chrislewispac/rfhq01L3/
with the following code:
var var1 = "value";
var var2 = "value";
var array = [var1,var2];
var array2 = [[var1,var2]];
console.log(array);
console.log(array2);
Go there and look at the console. You will notice the length of array2 is only 1 while the length of array is 2. So, you need to define your variables, then build the array in the format you want it (do you really want an array of arrays?) Then you can loop and add properties.
Also, an object means something in javascript. In javascript it is typical to see an object created using object literal syntax.
Object = {
property1 : "property",
property2: "property"
}
So when you asked if you could have an array of object, yes you can. However you have to create those objects and their properties first.

Related

Javascript how can I calculate total price in an array of items?

I'm new to js and have a cart in a webstore I am making for a Javascript assignment, and I can't get my total price working which displays on the webpage when the user clicks on items to add to the cart. Here is my array of items, any help would be appreciated, thank you
var cart;
var items = new Array(); //create array to store items
items[0] = "Greatest Hits CD", 10;
items[1] = "Girls CD", 10;
items[2] = "Shirt1", 20;
items[3] = "Mask Tee", 20;
items[4] = "Crewneck", 25;
items[5] = "Tour Poster", 9;
and here is my display function
this.display = function () {
this.holder.innerHTML = "";
this.totalprice = 0;
for (var i=0; i<this.quantities.length; i++) {
if (this.quantities[i] > 0) {
this.totalprice += this.quantities[i]*this.items[i];
var elm = document.createElement('div');
elm.innerHTML = "<span class='name'>"+this.items[i]+" \</span><span class='quantity'>Quantity: "+this.quantities[i]+"</span>";
this.holder.insertBefore(elm, null);
}
}
var elm = document.createElement('div');
elm.innerHTML = "<span class='price'>Total Price: $"+this.totalprice+" </span>";
this.holder.insertBefore(elm, null);
document.getElementById('quantities').value = cart.quantities;
document.getElementById('items').value = cart.items;
}
Array Reduce method is great for that, especially with the combination of Array destruct, since we only care about the price:
var items = [
["Greatest Hits CD", 10],
["Girls CD" , 10],
["Shirt1" , 20],
["Mask Tee" , 20],
["Crewneck" , 25],
["Tour Poster" , 9]
];
console.log(
items.reduce((total, [,price]) => total + price, 0)
);
You are trying to create an associative array (key/value pairs), which isn't how standard arrays work in JavaScript.
Instead, create an array of objects that store the data. Each "record" will be persisted as an object and those objects will each get a common set of property names (prop1 and prop2 in my example). You can then loop through the array of objects and upon each iteration, grab the property you are interested in (prop2) in this case.
var items = new Array(); //create array to store items
// Each item in the array will store an object with 2 properties
// Object literal syntax: {propertyName : propertyValue, propertyName : propertyValue, etc.}
items[0] = {prop1:"Greatest Hits CD", prop2:10};
items[1] = {prop1:"Girls CD", prop2:10};
items[2] = {prop1:"Shirt1", prop2:20};
items[3] = {prop1:"Mask Tee", prop2:20};
items[4] = {prop1:"Crewneck", prop2:25};
items[5] = {prop1:"Tour Poster", prop2:9};
var sum = null; // Place to store the total cost
// The JavaScript Array.prototype specifies a built-in method called
// forEach that takes a function as an argument. That function is
// automatically passed 3 arguments and is executed for each element
// in the array.
items.forEach(function(value, index, arry){
sum += value.prop2;
});
console.log(sum);

Js: multidimensional array literal declared: Add elements

I wanted to know if its possible to ad elements to an array which is declared as the following...
Please check the add() function, I can't figure out how to solve this problem. Thanks
It's not necessary, but I'd appreciate if you give an explanation since of c++ point of view programmer.
// My array is this way declared
var myArray = [
['John', 'Doe', '1980'],
['Jane','Malloy','1982'],
['Vincent','Malloy','1972']
];
// then I want to add a new elements in it, but It seems to doesn't work
var add = function() {
//var textbox = document.getElementById('textbox').value;
// storing new person in array
myArray [3][0] = 'New1';
myArray [3][1] = 'New2';
myArray [3][2] = 'New3';
};
//finally this function is for displaying the elements of myArray
var show = function() {
// clean output
document.getElementById('output').innerHTML = '';
// delay time
setTimeout (function() {
// showing info. people
for (var i in myArray) {
for (var j in myArray)
document.getElementById('output').innerHTML += myArray[i][j] + ' ';
document.getElementById('output').innerHTML += '<br/>';
}
}, 250);
};
So right here:
var add = function() {
//var textbox = document.getElementById('textbox').value;
// storing new person in array
myArray [3][0] = 'New1';
myArray [3][1] = 'New2';
myArray [3][2] = 'New3';
};
You can't add to myArray[3] because myArray[3] is undefined. You need to assign an empty array to myArray[3] first:
myArray [3] = [];
myArray [3][0] = 'New1';
myArray [3][1] = 'New2';
myArray [3][2] = 'New3';
Or more generally, assuming the idea is to add to the end of your array, you could do something like:
var idx = myArray.length;
myArray[idx] = [];
myArray[idx][0] = "New 1";
// ...
Or even something like:
var newArray = ["New1", "New2", "New3"];
myArray.push(newArray);

Combining results into one object

I'm looping through a set of inputs. I need to tally up the grouped totals. The inputs below to one of three categories.
How do I go about combining the values up relevant to three categories?
var compoundedArray = new Array();
holder.find(".dataset input").each(function(index) {
var val = $(this).val();
var dataType = $(this).data("type");
var localObj = {};
localObj[dataType] = val;
compoundedArray.push(localObj);
});
I have an object like this
[
{
"growth":30
},
{
"growth": 40
},
{
"other": 20
}
]
how do I loop through the object to produce something like
[
{
"growth": 70
},
{
"other": 20
}
]
if I looped over the initial array object
for (var i = 0; i < compoundedArray.length; i++) {
console.log(compoundedArray[i]);
}
how would I go about checking to ensure I don't have duplicates - and that I can tally up the results?
Ideally the resulting format may be the best
var array = [
"matching": 50,
"growth": 20
]
var array = [
"matching": 50,
"growth": 20
]
is not valid JS, but you can create an object of the form
var obj = {
"matching": 50,
"growth": 20
};
And that's pretty easy to do, just use an object from the very beginning:
var result = {};
holder.find(".dataset input").each(function(index) {
var val = +$(this).val(); // use unary plus to convert to number
var dataType = $(this).data("type");
result[dataType] = (result[dataType] || 0) + val;
});
Further reading material:
MDN - Working with Objects
Eloquent JavaScript - Data structures: Objects and Arrays
You can just use an object (not array) with unique keys.
var compoundedObj = {};
$(".dataset input", holder).each(function() {
var dataType = $(this).data("type");
if(!compoundedObj.hasOwnProperty(dataType)) {
compoundedObj[dataType] = 0;
}
compoundedObj[dataType] += parseInt($(this).val(), 10);
});
In this way you'll get an object like this:
{
"growth": 70,
"other": 20
}
Live demo
http://jsfiddle.net/GFwGU/
var original = [{"growth":30},{"growth": 40},{"other": 20}]
// object to sum all parts by key
var sums = {}
// loop through original object
for(var index in original){
// get reference to array value (target object)
var outer = original[index]
// loop through keys of target object
for(var key in outer){
// get a reference to the value
var value = outer[key]
// set or add to the value on the sums object
sums[key] = sums[key] ? sums[key] + value : value
}
}
// create the output array
var updated = []
// loop through all the summed keys
for(var key in sums){
// get reference to value
var value = sums[key]
// create empty object
var dummy = {}
// build object into desired format
dummy[key] = value
// push to output array
updated.push(dummy)
}
// check the results
alert(JSON.stringify( updated ))
var add=function (a,b){ a=a||0; b=b||0; return a+b};
var input=[ {growth:30},{growth:40},{other:20} ],output=[],temp={};
$.each(input,function(i,o){
var n;
for(i in o)
{n=i;break}
temp[n]=add(temp[n],o[n]);
});
$.each(temp,function(i,o){
var k={};
k[i]=o;
output.push(k)
});

need help javascript array = [] and how to output name of variable in array with value

I have a question about array as below
array = {}
and
array = [];
its same or not?.
also wish to ask
array { ID1 : "apple", ID2 : "Orange"}
and
array [ID1 : "apple", ID2 : "Orange"];
which is correct?.
now i coding my code with below and need your help to teach me about ARRAY.
var Store = [ store = 0, store1 = 0, store2 = 0,store3 = 0,store4 = 0];
var stock1 = 77,stock2 = 47,stock3 = 37,stock4 = 27,stock5 = 17;
for(i=0;i<stock1;i++){
store[0]++
}
var Sum_1 = Store;
document.getElementById('show1').innerHTML=Sum_1;
output will be
77
my question is how to i output it become
store = 77
store1 = 47
store2 = 37
Most with ID or Name together and value.
Thank you so much.
[] are used for a literal Array declaration, {} for a literal Object declaration.
Arrays are initialized without a value by using:
var my_array = [];
and with values:
var my_array = [1, 2, 3];
Note that you cannot set the index by this. You would have to do:
var my_array = [];
my_array["one"] = 1;
// etc.
You can then get "1" back by my_array["one"]
If you want to get the actual index name or "key" then you will need to do some trickery:
var outputString = "";
function ListAll()
{
for(var key in my_array)
{
if(my_array.hasOwnProperty(key)) // Check if the key is actually a property (index)
{
outputString += key + " = " + my_array[key]; // add to string
}
}
alert(outputString); // or assign the string to a div, whatever you need
}
in this example, key would be the index and my_array[key] the actual value

How to list multiple variables into a single variable in JavaScript?

This is probably a really basic question, but either there is no answer on the web or I'm not using the correct terminology. I want to store two separate variables (A and B) into 1 master variable, so that master = A then B.
So if A = 3, B = 8, master would equal 38. Anyone know how to do this in JavaScript? I'm not a programmer but here is my attempt.
var A = 1;
var B = 5;
var master = A, B;
document.write(master);
You seem to be requesting string concatenation. If you want an array, use one of the other answers. Otherwise: var master = A.toString() + B.toString(); See this JSFiddle.
Use an array:
var A = 1,
B = 5;
var master = [A, B];
master[0]; // 1
master[1]; // 5
Both objects and arrays are OK, as has been suggested. I'll just throw in another suggestion - an encapsulation ;)
function Master(a, b) {
this.first = a;
this.second = b;
this.both = function() {
return a + '' + b;
}
}
And to use it
var a = 3;
var b = 8;
var m = new Master(a, b);
alert(m.first); // 3
alert(m.second); // 8
alert(m.both()); // 38 (mind the parentheses, this is a function call!)
I know you said you're new, so I probably shouldn't being throwing arrays on you. However, for the others...
If you plan to get more dynamic than a few variables, you might want to invest in arrays.Put them into an array, then loop through the array printing them out as a string into a variable.
var myArray = new Array();
myArray.push(3);
myArray.push(8);
var myString = "";
for(var a = 0; a < myArray.length; a++)
{
myString += myArray[a].toString();
}
let 1st_new = [ [ 123, 'jack', 'white', 'tehran' ];
let 2nd_new= [ 456, 'roz', 'black', 'theran' ] ];
let 1st_list.push("1");
let 2st_list.push("2");
console.log(1st_new);
console.log(2nd_new);
#or you could make vairables of thge lists and put it inside a "var master" and print that out.

Categories