Undefined push when trying to insert to array - javascript

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

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

making JSON from string

I have a job to refractor strings to start using json so they can just pass json objects. So I have made array of names and then I'm trying to go through and make key and values but I'm getting an error in the console that it cant find x of no value. Can someone point me in the right direction?
var newName = ['ManagingOrg', 'ActiveOrg', 'Severity', 'SeverityClassification', 'WorkQueue', 'TicketState',................ to long to post];
$().each(newName, function (key, value) {
key = newName[this];
value = newValues[this] = $('#' + key).val();
newArray = [key][value];
newArray = JSON.stringify(newArray);
alert(newArray);
$('.results').html(origArray[TicketNumber]);
});
I'm assuming you have "newValues" and "origArray" defined elsewhere?
In any case you'll need to at least adjust the following:
"$().each" should be $.each
"newArray" should be defined outside and you should use newArray[key] = value
you don't have a variable "TicketNumber" defined and so you should wrap "TicketNumber" in quotes
this is a reserved word so you shouldn't use it in "newName[this]" or "newValues[this]"
I suggest using a for loop instead of $.each() based on what you're trying to do inside.
https://msdn.microsoft.com/en-us/library/bb299886.aspx
var origArray = [];
var newName = ['ManagingOrg', 'ActiveOrg', 'Severity', 'SeverityClassification'
];
for (var i = 0; i < newName.length - 1; i++) {
var object = {};
object[newName[i]] = newName[i];
object = JSON.stringify(object);
origArray.push(object);
}

Creating array of arrays with JavaScript

I have the following code, which when run gives error: TypeError: Cannot read property 'split' of undefined
Here you can run it.
var myData = "some1,some2,some3\nsome4,some5,some6\nsome7,some8,some9";
var arrayed = myData.split('\n');
var columns = arrayed.length;
var urlArray = new Array(columns);
console.log(arrayed);
var newarrayed = arrayed.split(',');
console.log(newarrayed);
I have myData array, I want to convert it to an array of arrays, splitting first at \n to seperate arrays, and second at , to create the items inside the arrays. so this list would be like:
[[data1, data2, data3], [data4, data5, data6], [data7, data8, data9]]
console.log(arrayed); does something similar, but when I try to access it using arrayed[0][0], it gives me just the first letter.
You're not splitting the strings correctly. You try to split them twice, but the second time fails because you are calling split on an array, not a string. Try looping over them instead.
var myData = "some1,some2,some3\nsome4,some5,some6\nsome7,some8,some9";
var arrayed = myData.split('\n');
var columns = arrayed.length;
var urlArray = new Array(columns);
console.log(arrayed);
var newarrayed = [];
for (var i in arrayed) {
newarrayed.push(arrayed[i].split(','));
}
console.log(newarrayed);

How to parse read json elements with jquery

I have to create cart system in my mobile application, i want to store the id and the quantity of products, the id should be the key of my array (for modifying product quantity) , tried to use object instead of array but i get error: undefined is not a function when i try to read my json variable
by JSON.stringify(cart)
My cart code is like this
var cart = [];
var produit = {};
produit['qte'] = $('.'+id_prd).text();
produit['id_produit'] = id_prd;
cart[id_prd] = produit;
window.sessionStorage["cart1"]= JSON.stringify(cart);
return me
{"7":{"qte":"1","id_produit":7},"8":{"qte":"1","id_produit":8}}
when I tried to parse the json string with
var parsed = $.parseJSON(window.sessionStorage["cart1"]);
i get the error 'undefined is not a function'
when triying to read the json with
var i=0;
for (k in parsed) {
var k_data = parsed[k];
k_data.forEach(function(entry) {
alert(entry);
ch+=entry.id_produit;
if(i<parsed.length-1)
ch+= ',';
if(i==parsed.length-1)
ch+=')';
i++;
});
}
Can you clarify me the error cause, and if there's a solution to better read the json
The problem is that you are using k_data.forEach(function(entry) but forEach is for Arrays, and k_data is just a simple javascript object.
Try changing:
k_data.forEach(function(entry){
to this:
$(k_data).each(function(entry){
Even more, if the JSON is always in the same structure you posted, I think the each function is not necessary, maybe this is the way you are looking for:
var i=0;
var ch = "(";
for (k in parsed) {
var k_data = parsed[k];
alert(k_data);
ch+=k_data.id_produit;
ch+= ',';
i++;
}
ch = ch.substring(0, ch.length - 1) + ")";
You shouldn't need jQuery for this. The same JSON object you used to stringify has a parse function:
var parsed = JSON.parse(window.sessionStorage["cart1"]);
If that still breaks, there's probably something wrong with another undefined object.
You can try something like this:
<script type="text/javascript">
var finalArr = new Array();
var dataArr = new Array();
dataArr = window.sessionStorage["cart1"];
if (JSON.parse(dataArr).length > 0) {
for (var i = 0; i < JSON.parse(dataArr).length; i++) {
finalArr.push((JSON.parse(dataArr))[i]);
}
}
</script>

How to separate the values from two dimension array in js?

jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
$('#div1').append(msgid);
$('#div2').append(rspid);
});
Let's say the value of newitems is [["320","23"],["310","26"]]
I want to assign "320" and "310" to var msgid.
I want to assign "23" and "26" to var rspid.
How to do that?
I tried to display newitems and the output is "Array". I tried to display newitems[0] and the output is blank.
If I redeclare var newitems = [["320","23"],["310","26"]]; it works. So I guess the variable newitems from jQuery.get is something wrong. Is it I cannot pass the array from other page to current page through jQuery directly?
Regarding the array on other page, if echo json_encode($Arraytest); the output is [["320","23"],["310","26"]] but if echo $Arraytest; the output is Array. How do I pass the array from other page to currently page by jQuery.get?
I don't totally understand the question but I'm going to assume you want the values in an array, as two values can't be stored in one (scalar) variable simultaneously.
jQuery.get("ChkNewRspLive.php?lastmsgID=" + n, function(newitems){
//some code to separate values of 2d array.
var msgid = [],
rspid = [];
for( i = 0 ; i < newitems.length ; i++){
msgid[msgid.length] = newitems[i][0];
rspid[rspid.length] = newitems[i][1];
}
//msgid now contains ["320","310"]
//rspid now contains ["23","26"]
});
Bear in mind those are in the function scope. If you want to use them outside of that scope instantiate them outside. see: closure
You can use pluck from underscore.js: http://documentcloud.github.com/underscore/#pluck
var msgid = _(newitems).pluck(0)
var rspid = _(newitems).pluck(1)
Try this:
function getArrayDimension(arr, dim) {
var res = [];
for(var i = 0; i < arr.length; i++) {
res.push(arr[i][dim]);
}
return res;
}
var newitems = [["320","23"],["310","26"]];
var msgid = getArrayDimension(newitems, 0);
var rspid = getArrayDimension(newitems, 1);
msgid and rspid are arrays holding the 'nth' dimention.
Tnx

Categories