How to add data to a 2-D map in Javascript - 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

Related

Adding key to multiple values in an object

I am looking to grab a string value from a text box and multiple values from a multiselect list and associate them where the string value is the key, and the multiple values from the drop down list are the values.
Here is the javascript code I have thus far:
var serviceName = document.getElementById('servicePackageText').value;
var sourceType = document.getElementById("multiple-checkboxes");
var groupName = serviceGroupName;
var serviceArray = new Array();
for (i = 0; i < sourceType.selectedOptions.length; i++) {
serviceArray.push(parseInt(sourceType.selectedOptions[i].value));
}
I want the format to look like this:
"Textbox value": [
multiselect_values,
multiselect_values,
multiselect_values,
multiselect_values
]
Any tips on how to proceed?
You need wrapper object, then it is easy. All you have to do is use [] property accessor to assign the object property.
I took some liberty with your code to make it simpler to rationalize:
var serviceName = "myDog"; //mock document.getElementById('servicePackageText').value;
var sourceType = [1, 2, 3, 4]; //mock document.getElementById("multiple-checkboxes");
var groupName = {};
groupName[serviceName] = sourceType; // <--- THE ANSWER
console.log(groupName);

Undefined push when trying to insert to array

I'm new to Javascript, I wanted to push all the data inside my text file to array, it works fine I do this:-
var pokemon_array = [];
$.get('pokemonlist.txt', function(data) {
var lines = data.split('\n');
for(var i=0;i<lines.length;i++) {
var arr = lines[i].split('"');
pokemon_array.push(arr[1]);
pokemon_array.push(arr[3]);
pokemon_array.push(arr[4]);
}
console.log(pokemon_array);
});
I wanted it to have 2 dimensional array so I put this:-
var pokemon_array = [];
$.get('pokemonlist.txt', function(data) {
var lines = data.split('\n');
for(var i=0;i<lines.length;i++) {
var arr = lines[i].split('"');
pokemon_id = arr[1];
pokemon_img = arr[3];
pokemon_name = arr[4];
pokemon_array[i].push(pokemon_id);
pokemon_array[i].push(pokemon_img);
pokemon_array[i].push(pokemon_name);
}
console.log(pokemon_array);
});
Then I received this error:-
Uncaught TypeError: Cannot read property 'push' of undefined
Anything I did wrong here?
Change
pokemon_array[i].push(pokemon_id);
pokemon_array[i].push(pokemon_img);
pokemon_array[i].push(pokemon_name);
to
pokemon_array.push([ pokemon_id, pokemon_img, pokemon_name ]);
otherwise pokemon_array[i] is not there yet.
Also you'd better either declare your pokemon_... variables with var or just do pokemon_array.push([ arr[1], arr[3], arr[4] ]); if the only use for them is to be added to array.
The problem is that pokemon_array[i], which would be pokemon_array[0], pokemon_array[1] etc. was never assigned.
You can change the code to something like:
pokemon_array[i] = [];
pokemon_array[i].push(pokemon_id);
pokemon_array[i].push(pokemon_img);
pokemon_array[i].push(pokemon_name);
Or
pokemon_array[i] = [pokemon_id, pokemon_img, pokemon_name];
Or you can just write it shorter because you can just use the array you have:
pokemon_array[i] = arr;
But you don't need the [i] at all really, so you can go like:
pokemon_array.push([pokemon_id, pokemon_img, pokemon_name]);
which can be even shorter as mentioned above:
pokemon_array.push(arr);
This does not just append each element in arr. It adds the entire arr as one element of pokemon_array, as you want exactly.
You get the error because pokemon_array[i] is undefined
pokemon_array[i].push(pokemon_id);
pokemon_array[i].push(pokemon_img);
pokemon_array[i].push(pokemon_name);
to
pokemon_array.push(pokemon_id);
pokemon_array.push(pokemon_img);
pokemon_array.push(pokemon_name);

Javascript multidimensional array not working

How to create multidimensional array??
I tried it so far:
var post_data = [];
var id = 1;
post_data[id] = [];
post_data[id]['name'] = 'abc';
post_data[id]['date'] = '01-03-2014';
post_data[id]['country'] = 'India';
console.log(post_data);
the above code is not giving me the key. Whats wrong?
DEMO FIDDLE
i want a output something like this:
[1]=> array
(
"name": "abc",
"date": "01-03-2014",
"country": "India",
)
How to get the above output???
To get wished result you can change
var post_data = [];
to
var post_data = {};
and
post_data[id] = {};
You are trying to make an array of object.
Try this : -
post_data[id] = {};
You are using the inner array as an object. The properties that you set on the array still is there, when you display it only the array items are shown.
You should use an object instead of an array, as you are not using the array as an array:
post_data[id] = {};
Instead of setting the properties after creating the object, you can set them when you create it:
post_data[id] = {
name: 'abc',
date: '01-03-2014',
country: 'India'
};
In the third line of code you have to write
post_data[id] = new Array();
So the entire code section looks like
var post_data = [];
var id = 1;
post_data[id] = new Array();
post_data[id]['name'] = 'abc';
post_data[id]['date'] = '01-03-2014';
post_data[id]['country'] = 'India';
console.log(post_data[id]['name']);
This should fix it, best of luck :)

Setting dynamically an Object in JavaScript

It seems complicated for me.
First, I have this list:
liste_path_categories.push(
{ index: null
, letter: "letter1"
, type: key
, picture_url: "url1"
, id_categ: null
, response: "Answer here"
});
What I want is to extract from this big list an object in this form:
data["String1"]["String2"]= String3
With :
String1=list_path_categories[i].letter
String2=list_path_categories[i].id_categ
String3=list_path_categories[i].response
example:
data['A']['12'] : "A_answer"
To declare the data i make this:
var data = new Object(new Object);
How I can set all the values in data?
You can use the Array.forEach method to iterate through liste_path_categories and construct your data object.
Example:
var liste_path_categories = [];
var data = {};
liste_path_categories.push(...);
...
liste_path_categories.push(...);
liste_path_categories.forEach(function(element) {
data[element.letter] = {};
data[element.letter][element.id_categ] = element.response;
});
jsFiddle example : http://jsfiddle.net/3ZvNf/
Your question is pretty vague but do you mean something like this?
Setting a dynamic property in an object wich belongs to another object?
data['A']['12'].answer = "A_answer"
Instead of using strings, you have to use the variables in your property access:
var data = {};
if (!data[String1]) {
data[String1] = {}; // make sure that data[String1] exists and is an object
}
data[String1][String2] = String3;
If you want to do this for elements in the array, you have to iterate over the array.
P.S.: I recommend to use more expressive variable names than StringX.
first create the constructor (in OOP terminology):
var ctor_object = function(letter,id_categ,response)
{
this.letter = letter;
this.id_cated = id_categ;
this.response = response;
}
(in genereal you should omit the ctor_ syntax and name it directly after the name of the class of your object)
then use your constructor upon your list of categories:
var length = liste_path_categories.length,
element = null;
for (var i = 0; i < length; i++)
{
element = liste_path_categories[i];
my_obj = new ctor_object(element.letter,element.id_categ,element.reponse)
// Do something with my_obj
}

For loop into array in a certain format

I've been trying to create an array from a for loop, using push which creates an array in the format ["value, value, value, value, value, value"] but I need it to create an array in the following format: [["value, value, value"],["value, value, value"]
The original array is created without a for loop like this:
new array (["1","2",3"],["1,2,3"],["1,2,3"],["1,2,3"]);
so how do I go about creating the same using a loop instead?
var colour = ["red","green","blue","orange"];
for (i=1; i<5; i++){
var name = $("#name"+i).val();
var can = $("#candidate"+i).val();
arrayOfData = new Array([can,name,colour[i]]);
}
Just push your arrayOfData itself to an array.
var array = [];
var colour = ["red","green","blue","orange"];
for (i=1; i<5; i++){
var name = $("#name"+i).val();
var can = $("#candidate"+i).val();
arrayOfData = [can,name,colour[i-1]];
array.push(arrayOfData);
}
​
Demo here: http://jsfiddle.net/f5J5z/4/

Categories