javaqscript: 2d associative arrays 101 - javascript

This is my first Q&A ever, so hopefully it's alright.
As someone who generally picks stuff up quickly, I found the information on this topic was sporadic and generally over complicated, with many people saying it simply couldn't be done. so here's it broken down very simply.
Take this scenario as an example, we have a number of form components (text boxes, buttons, etc.), all with a number of properties, all of which have values... and we want to store these in a javascript array.

Here's my tinkerings. This code doesn't explicitly answer a question, as no question was explicitly asked, however I hope you find it useful
For good measure, here also is a jsfiddle http://jsfiddle.net/cQ8Xc/
var $parent_arr = new Array();
var $child_arr = new Array();
//we can add the key => value pairs like so:
//(obviously they won't be done like this, more likely a loop for example)
//this works just fine $child_arr[$key] = $value;
$child_arr['Top'] = '12';
$child_arr['Left'] = '13';
$child_arr['Right'] = '14';
$child_arr['Bottom'] = '15';
//we can add the array to another array like so:
$parent_arr['component1'] = $child_arr;
//clear the array for reuse (note that it is obviously not nessecary to reuse the array)
$child_arr = [];
//refill it
//note that the child arrays don't have to be identical lengths or values
$child_arr['Height'] = '22';
$child_arr['Width'] = '23';
$child_arr['Colour'] = 'blue';
$parent_arr['component2'] = $child_arr;
//we can access the data like this:
alert($parent_arr['component1']['Top']);
alert($parent_arr['component2']['Colour']);
//these didn't work for me, you've likely seen them in other answers if you've been researching this topic
//alert(JSON.stringify($parent_arr['component1'], null, 4));
//alert(JSON.stringify($parent_arr['component1']));
//alert($parent_arr['component1'].join("\n"));
//the array can be looped over like so:
for(var component in $parent_arr) {
for(var propertyName in $parent_arr[component]) {
alert(component + '.' + propertyName + '=' + $parent_arr['component1'][propertyName]);
}
}

Related

Add values to end of multidimensional array

I have an array of arrays and I want to be able to add values to the array every time a user hits the add button.
var transactions = [];
transactions[0] = []; // holds date
transactions[1] = []; // holds transaction type
transactions[2] = []; // holds amount
transactions[0][i] = $("date").value;
transactions[1][i] = $("transType").value;
transactions[2][i] = parseFloat( $("amount").value);
these are the snippets . . . I realize I need to work on validation (which I will do) at this point I'm more concerned with loading the arrays. The problem is the method I'm familiar with works with 1-dimensional arrays and I don't know how to replace it.
in short is it possible to reproduce this:
transactions[transactions.length] = $("date").value;
for a multidimensional array.
Thank You
Use push:
transactions[0].push( $("date").value );
You're looking for the Array.push() method. It allows you to push values on to the end of an array.
For your use case, you can do that on both levels of the array. See below:
var transactions = [];
transactions.push([]);
transactions.push([]);
transactions[0].push( $('date').value );
There is no problem for using the same approach:
transactions[0][transactions[0].length] = $("date").value;
or with push method:
transactions[0].push($("date").value);
... keeping in mind that you've initialized transactions[0] with empty array [].
Yes, just idem for multidimensional
transactions[0][transactions[0].length] = var1;
Seems a little weird you are doing:
[[array of transaction dates],[array of transaction types],[array of transaction amounts]]
Are you sure you don't want
[array of transactions, with date,type,amount properties]
?
var transactions = [];
transactions.push({'date': $("date").value, 'type': $("transType").value, 'amount': parseFloat( $("amount").value)});
var i = 0;
alert('date ' + transactions[i].date + ' type ' + transactions[i].type + ' amount ' + transactions[i].amount);

arranging elements in to a hash array

I am trying to break a javascript object in to small array so that I can easily access the innerlevel data whenever I needed.
I have used recursive function to access all nodes inside json, using the program
http://jsfiddle.net/SvMUN/1/
What I am trying to do here is that I want to store these in to a separate array so that I cn access it like
newArray.Microsoft= MSFT, Microsoft;
newArray.Intel Corp=(INTC, Fortune 500);
newArray.Japan=Japan
newArray.Bernanke=Bernanke;
Depth of each array are different, so the ones with single level can use the same name like I ve shown in the example Bernanke. Is it possible to do it this way?
No, you reduce the Facets to a string named html - but you want an object.
function generateList(facets) {
var map = {};
(function recurse(arr) {
var join = [];
for (var i=0; i<arr.length; i++) {
var current = arr[i].term; // every object must have one!
current = current.replace(/ /g, "_");
join.push(current); // only on lowest level?
if (current in arr[i])
map[current] = recurse(arr[i][current]);
}
return join;
})(facets)
return map;
}
Demo on jsfiddle.net
To get the one-level-data, you could just add this else-statement after the if:
else
map[current] = [ current ]; // create Array manually
Altough I don't think the result (demo) makes much sense then.

Issue with JSON stringify?

/* Helper function to clean up any current data we have stored */
function insertSerializedData(ids, type) {
// Get anything in the current field
current_data = $('#changes').val();
if (!current_data) {
var data = new Array();
data[type] = ids;
$('#changes').val(JSON.stringify(data));
} else {
var data = JSON.parse($('#changes').val());
data[type] = ids;
$('#changes').val(JSON.stringify(data));
}
console.log($('#changes').val());
}
I am using the following function to either add data to a current JSON object or create a new JSON object all together to be used in PHP later. Is the stringify() method only for FF? I am using google chrome and I am being given an empty object when using the conosole.log() function...
Also what happens if you try to store two values with the same key? I assume it will overwrite...so I should add a random math number at the end array in order to keep duplicates from showing up?
Thanks :)
These lines may cause problems:
var data = new Array();
data[type] = ids;
... because arrays in JavaScript are not quite like arrays in PHP. I suppose what you meant is better expressed by...
var data = {};
data[type] = ids;
Besides, current_data seems to be local to this function, therefore it also should be declared as local with var. Don't see any other problems... except that similar functionality is already implemented in jQuery .data() method.
UPDATE: here's jsFiddle to play with. ) From what I've tried looks like the array-object mismatch is what actually caused that Chrome behavior.
I reformatted it a bit, but and this seems to work. It will set the "value" attribute of the #changes element to a JSON string. I assume that the type argument is supposed to be the index of the array which you're trying to assign?
function insertSerializedData(ids, type) {
var changes = jQuery('#changes'), arr, val = changes.val();
if (!val) {
arr = [];
arr[type] = ids;
changes.val(JSON.stringify(arr));
} else {
arr = JSON.parse(val);
arr[type] = ids;
changes.val(JSON.stringify(arr));
}
console.log(changes);
}

Object - An Object in the Object - An array of those Objects

I'm new to javascript so let me just say that right up front.
A web site I frequent has 50 or so items, with details about that item, in a table. Each table row contains several td cells. Some rows have types of things that are similar, like USB drives or whatever. I want to capture each row so that I can group and reorder them to suit my tastes.
I have this object:
function vnlItemOnPage(){
this.Category = "unknown";
this.ItemClass = "vnlDefaultClass";
this.ItemBlock = {};
}
This represents one row.
What I've been trying to figure out is how to capture the block of html < tr>stuff< /tr> and save it into this.ItemBlock.
That part is pretty easy:
vnlItemOnPage.ItemBlock = element.getElementByClassName('className')[0]
?
That seems pretty straight forward. Am I missing something?
This part I am stuck:
There'll be 50 of them so I need an array of vnlItemOnPage?
vnlAllItems = ???
var vnlAllItems = [vnlItemOnPage]?
And, how would I add to the array and delete from the array? I probably wont delete from the array if that is complicated don't bother with it.
Once I capture the < tr> html, I can just append it to a table element like so:
myTable.appendChild(vnlAllItems[0].ItemBlock);
Correct?
I'm open to any suggestions if you think I'm approaching this from the wrong direction. Performance is not a big issue - at least right now. Later I may try to conflate several pages for a couple hundred items.
Thanks for your assistance!
[edit]
Perhaps the second part of the question is so basic it's hard to believe I don't know the answer.
The array could be: var vnlAllItems = []
And then it is just:
var row1 = new vnlItemOnPage;
vnlAllItems.push(row1);
var row2 = new vnlItemOnPage;
row2.ItemBlock = element.getElementByClassName('className')[0];
I'd like to close the question but I hate to do that without something about handling the array.
JQuery is your friend here.
This will give you the inner HTML for the first row in the body of your desired table:
var rowHtml = $('table#id-of-desired-table tbody tr:first').html() ;
To get the outer HTML, you need a jQuery extension method:
jQuery.fn.outerHTML = function() {
return $('<div>').append( this.eq(0).clone() ).html();
};
Usage is simple:
var rowHtml = $('table#id-of-desired-table tbody tr:first').outerHtml() ;
Enjoy!
Not sure if it is what you are looking for, but if I wanted to manipulate table rows I would store:
Row's whole html <td>1</td>...<td>n</td> as string so I can quickly reconstruct the row
For each row store actual cell values [1, ..., n], so I can do some manipulations with values (sort)
To get row as html you can use:
var rowHtml = element.getElementByClassName('className')[0].innerHTML;
To get array of cell values you can use:
var cells = [];
var cellElements = element.getElementByClassName('className')[0].cells;
for(var i=0;i<cellElements.length;i++) {
cells.push(cellElements[i].innerText);
}
So the object to store all this would look something like:
function vnlItemOnPage(){
this.Category = "unknown";
this.ItemClass = "vnlDefaultClass";
this.RowHtml = "";
this.RowCells = [];
}

Javascript and HTML data model and presentation model design question

so I've been working on a project in Javascript that takes in objects the user provides and represents them in HTML. Right now they are represented in memory as an array, and in the display as a separate array. After integrating some code changes, problems have arisen in that the display array seems to be having troubles removing it's contents, thus things that should be removed don't disappear from the view.
Declaring lists:
this.divList = gDocument.getElementById( element );
this.objectList = [];
Adding an object to the lists:
addObject = function (address, type){
var newDiv = gDocument.createElement("div");
this.divList.appendChild( newDiv );
var d = this.createObject( newDiv, address, type );
if (undefined != d)
{
this.objectList.push(d);
}
}
The divList accurately reflects the objectList until any changes are made to the objectList at runtime. When restarted, the lists are in sync once again. When I tried to fix it, things were very complicated. I'm wondering if there is a better way to design such an idea (the object model and the graphical representation). Any comments would be helpful, thanks.
Question vagueness aside, my recommendation would be to store one list, not two, in memory. Each list element is an object with all the necessary data you need for that particular abstract "object" (the ones that "the user provides"). Something like this:
this.divList = gDocument.getElementById(element);
this.masterList = [];
var i,
len = this.divList.length;
for (i = 0; i<len; i++)
{
this.masterList.push({
elt: this.divList[i],
obj: /* however you'd create the object in this.objectList */
});
}
Edit: your addObject function would be changed to something like this:
addObject = function (address, type)
{
var newDiv = gDocument.createElement("div"),
newObj = {elt: newDiv,
obj: this.createObject(newDiv, address, type)};
this.masterList.push(newObj);
this.divList.appendChild(newDiv);
}
You should store a reference to the HTML element that you're appendChild()ing to. You're already doing this - but when you need to manipulate the individual elements (say, remove one), use the masterList instead:
removeObject = function (i)
{
var toRemove = this.masterList.splice(i, 1);
if (toRemove)
{
this.divList.removeChild(toRemove.elt);
}
}
See also Array.splice().

Categories

Resources