Performing a foreach over an associative array of associative arrays - javascript

Suppose I have this setup:
var whatever = new Array();
whatever["a"] = new Array();
whatever["a"]["a"] = "test1";
whatever["a"]["b"] = "test2";
whatever["b"] = new Array();
whatever["b"]["a"] = "test3";
whatever["b"]["b"] = "test4";
And I attempt to iterate through it:
$.each(whatever, function(key, value) {
$.each(value, function(subkey, subvalue) {
//stuff with key, subkey, and subvalue here
});
});
Yet the iteration fails, commenting out the nested foreach loop will allow the page to load, so that appears to be where the problem is.
Inside the first loop, I can do something like:
alert(value["a"]);
and receive the proper value, so it seems to be a "valid" array. Where am I going wrong, since the nested loop is basically the same as the outer one?

Use objects instead of arrays.
var whatever = {};
whatever["a"] = {};
whatever["a"]["a"] = "test1";
whatever["a"]["b"] = "test2";
whatever["b"] = {};
whatever["b"]["a"] = "test3";
whatever["b"]["b"] = "test4";
http://jsfiddle.net/QwT8W/

Related

How to add data to a 2-D map in Javascript

I mostly develop in Java, but I presently need to do some work using JavaScript.
I have data that I need to group by two dimensions: first by gender, and then by language. The object to be grouped comes like so:
var items =[ {
"language":"english",
"gender":"male",
...//twelve other fields
},
...
]
This is what I've tried:
var myMap = {};
for(var i=0; i<items.length;i++){
var item = items[i];
var _gender = item["gender"];
var _lang = item["language"];
myMap[_gender][_lang].push[item];
}
I assumed the above would work, but it’s not working. It keeps returning this error:
Uncaught TypeError: Cannot read property 'undefined' of undefined
Note: In Java, I would be creating a map of arrays.
One problem:
When you call myMap[_gender][_lang].push[item];, what you are actually doing is adding a key to the Object myMap, with the current value of _gender, and turning it into an Object, which you then create a new key for, set to the value of _lang. In addition, .push() is a function used with arrays, to add a new item onto the end of the array. If you want to add a new key and value to an Object, all you have to do is just call that key and assign it a value. Here's an example.
var obj = {
ex1 : 'example 1',
ex2 : 'example 2'
};
console.log(obj);
obj.ex3 = 'example 3';
console.log(obj);
//The code below will simply log 'undefined' in most consoles(it doesn't happen to do so in this snippet).
console.log(obj.ex4);
Here's my suggestion(assuming I correctly understand what you're trying to do):
var items = [{
"language":"english",
"gender":"male",
},
//...more below
];
myMap = [];
for(var i = 0; i < items.length; i++){
myArray = [];
var item = items[i];
var _gender = item["gender"];
var _lang = item["language"];
myArray.push(_gender);
myArray.push(_lang);
myMap.push(myArray);
}
You are doing totally wrong. First of all myMap is object not an array so you can not use myMap.push().
You can achieve like this.
var items = {
"language":"english",
"gender":"male"
}
var myMap = {};
for(var key in items){
var myArray = [];
var _gender = items["gender"];
var _lang = items["language"];
myArray.push(_gender);
myArray.push(_lang);
myMap.item = myArray;
console.log(myMap);
}
for add 2-d array read this. 2-D Array in javascript

Removing one item from multiple identical arrays

I am trying to remove items from arrays that are all the same. Interestingly, it works when my arrays are different. The following code works as intended, removing the Fireman from team1, the Pyromancer from team2, the Aronist from team3, and the Vigilante from team4.
var options = {};
options.characters = ["Fireman","Missionary","Vigilante","Corrupt Policeman","Suicide Bomber","Arsonist","Gunman","Pyromancer","Hypnotist","Picklock","Policeman","Child","Prostitute"];
this._team1Characters = options.characters.concat(["test1"]);
this._team2Characters = options.characters.concat(["test2"]);
this._team3Characters = options.characters.concat(["test3"]);
this._team4Characters = options.characters.concat(["test4"]);
var submissions = {};
submissions.character1 = "Fireman";
submissions.character2 = "Pyromancer";
submissions.character3 = "Arsonist";
submissions.character4 = "Vigilante";
var i = 5;
while(--i){
if(submissions["character"+i]){
this["_team"+i+"Characters"].splice( this["_team"+i+"Characters"].indexOf(submissions["character"+i]), 1 );
}
}
alert(this._team1Characters);
alert(this._team2Characters);
alert(this._team3Characters);
alert(this._team4Characters);
However, if the four arrays are the same, all arrays end up the same (all lack the Fireman, the Pyromancer, the Aronist and the Vigilante). This is the code causing the problem:
var options = {};
options.characters = ["Fireman","Missionary","Vigilante","Corrupt Policeman","Suicide Bomber","Arsonist","Gunman","Pyromancer","Hypnotist","Picklock","Policeman","Child","Prostitute"];
this._team1Characters = options.characters;
this._team2Characters = options.characters;
this._team3Characters = options.characters;
this._team4Characters = options.characters;
var submissions = {};
submissions.character1 = "Fireman";
submissions.character2 = "Pyromancer";
submissions.character3 = "Arsonist";
submissions.character4 = "Vigilante";
var i = 5;
while(--i){
if(submissions["character"+i]){
this["_team"+i+"Characters"].splice( this["_team"+i+"Characters"].indexOf(submissions["character"+i]), 1 );
}
}
alert(this._team1Characters);
alert(this._team2Characters);
alert(this._team3Characters);
alert(this._team4Characters);
What's the reason for this?
When you do this._team1Characters = options.characters; you're passing a reference, so you really end up with lots of references to the same array. Consequently, when you change that single array, you'll see the change through any of the references.
If you want to copy an array, use Array.prototype.slice().
this._team1Characters = options.characters.slice();
...
since you are assigning the reference of the same variable to all, so all the removals are essentially happening from same array options.characters
try doing it this way
this._team1Characters = options.characters.concat( [] );
this._team2Characters = options.characters.concat( [] );
this._team3Characters = options.characters.concat( [] );
this._team4Characters = options.characters.concat( [] );
this will ensure that all get the same values in a different array and values in other arrays are not affected when removed from one array

Error with declaring variables in for loop

I just want set 2 arrays which should contain for loop output.
Here's code:
var key_ls = new Array();
var value_ls = new Array();
for (var a in window.localStorage) {
key_ls[a] = a;
value_ls[a] = localStorage[a];
}
and it gives me no result. What do i wrong?
What you're looking for is key_ls.push(a), which will simply add another item to the array. Also use [] instead of new Array().

javascript fails when populating array

When I run the following javascript, it fails when input_array[input_array.length] = id; is not commented out. Can anyone see what is causing this?
function cat_images_low_lag () {
var input_array = new array ();
cat_images = $(".category-description").next().find("img");
cat_images.each(function () {
url = $(this).parent().attr("href");
id = url.split("id=");
id = id[1];
input_array[input_array.length] = id;
});
alert ("trst");
alert(input_array.join("\n"));
}
cheers!
First thing, replace:
var input_array = new array ();
With:
var input_array = new Array();
And use this to insert:
input_array.push(id);
Or directly add:
input_array[input_array.length] = id;
Other ways to initialize arrays:
var input_array = [];
Others noted the capitalization problem, but since you're using jQuery, a nicer way to build the Array is like this:
function cat_images_low_lag () {
var input_array = $(".category-description + * img").map(function () {
return this.parentNode.href.split("id=")[1];
}).toArray();
alert ("trst");
alert(input_array.join("\n"));
}
Your initialization of the array is incorrect
var input_array = new array ();
You should use the shorthand
var input_array = [];
or
var input_array = new Array();
Moreover, to avoid having cat_images be a variable in the global scope, you may want to consider scoping it locally like this
var cat_images = $(".category-description").next().find("img");

How can I use custom "class"(function) as array datatype in javascript?

I know in javascript if I want define an array,I use:
var arr=new array();
However,this array could only use for store date,int,string,just the javascript already defined
Suppose I have already my custom datatype:
function LayerInfo(uuid, top, left, index, pindex) {
this.uuid = uuid;
this.top = top;
this.left = left;
this.index = index;
this.pindex = pindex;
}
How can I initialize an array which the data type is the "LayerInfo",could store the "LayerInfo"?
like
var l=new LayerInfo()?
if this could be done ,how can I let the layerinfo push into the array,or pull it out?
However,this array could only use for store date,int,string,just the
javascript already defined
Fortunately not, arr can store any object you like, including instances of your LayerInfo:
var arr = new Array(); //note caps or var arr = [];
arr[i] = new LayerInfo();
arr[i] = someLaterInfoInstance;
arr.push(new LayerInfo()); ...

Categories