Not Able to Push Arrays into Array (Making Array of Arrays) - javascript

can you please take a look at this snippet and let me know why I am not able to create an array of array at this example?
var data1 = [5555,22,102858,12,.554,88888,99999999,12,1.5];
var data2 = [5555,22,102858,12,.554,88888,99999999,12,1.5];
var data3 = [5555,22,102858,12,.554,88888,99999999,12,1.5];
var data4 = [5555,22,102858,12,.554,88888,99999999,12,1.5];
var all = [];
all[0].push(data1);
all[1].push(data2);
all[2].push(data3);
all[3].push(data4);
var myJsonString = JSON.stringify(all);
console.log(myJsonString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You should be doing all.push(dataX) since all[X] is undefined.
var data1 = [5555,22,102858,12,.554,88888,99999999,12,1.5];
var data2 = [5555,22,102858,12,.554,88888,99999999,12,1.5];
var data3 = [5555,22,102858,12,.554,88888,99999999,12,1.5];
var data4 = [5555,22,102858,12,.554,88888,99999999,12,1.5];
var all = [];
all.push(data1);
all.push(data2);
all.push(data3);
all.push(data4);
var myJsonString = JSON.stringify(all);
console.log(myJsonString);
Explanation:
In the code you wrote, all is an empty Array.
all[X] (e.g. all[0]) refers to the first element of the array, which doesn't exist (since array is empty). JavaScript interprets this as undefined. (There is no array out of bounds exception)
undefined has no method .push(...) which is why your code is failing.
What you want is to call all.push(...) where you're calling .push(...) on the all Array.

all[0].push(data1);
all[0] retrieves the first element of all. Since you just made the array and it's empty, this is undefined. (In other languages, it would be an array index access violation). You're then trying to push onto that first element; if it were an array itself, this would give you [[[5555,22,... which is one more array container than you want.
Easiest solution is to construct the array via a literal.
var all = [data1, data2, data3, data4];
// no "push()" necessary here.

Related

pushing variables to array returns undefined

SOLVED, Thank you! I needed to specify the index.
I am trying to push a set of variables into an array from user input.
Without using push it is working fine;
var inputStart = addAppointment.inputStart.value;
var inputEnd = addAppointment.inputEnd.value;
var appointmentArr = [];
appointmentArr = {start:inputStart, end:inputEnd};
document.write(appointmentArr.start);
document.write(appointmentArr.end);
however, when I try to push the variables it returns undefined;
var inputStart = addAppointment.inputStart.value;
var inputEnd = addAppointment.inputEnd.value;
var appointmentArr = [];
appointmentArr.push({start:inputStart, end:inputEnd});
document.write(appointmentArr.start);
document.write(appointmentArr.end);
Can anyone explain why this is happening?
As far as I am aware I need to use push because I eventually want to create a new, populated index number every time the user inputs data, so any help is greatly appreciated.
Thanks in advance
You are accessing array.
So, the document.write part should be like this
document.write(appointmentArr[0].start);
document.write(appointmentArr[0].end);
Since appointmentArr is an array, you should fisrt take appointmentArr[0] to access the first element of the array.
After you push the value, the appointmentArr becomes, [{start:inputStart, end:inputEnd}]
Since, it is an array you cannot access object keys directly, you have to take specific index element and then can access them using appointmentArr[index]
var inputStart = 'inputStart';
var inputEnd = 'inputEnd';
var appointmentArr = [];
appointmentArr.push({start:inputStart, end:inputEnd});
document.write(appointmentArr[0].start + ' ');
document.write(appointmentArr[0].end);
Please run the above snippet
You re-assigned your variable as Object.
var appointmentArr = [];
appointmentArr = {start:inputStart, end:inputEnd};
This code overwrite appointmentArr from Array [] to Object { start:inputStart, end:inputEnd }
And in the second code:
var appointmentArr = [];
appointmentArr.push({start:inputStart, end:inputEnd});
You modify appointmentArr from Array [] to Array [ {start:inputStart, end:inputEnd} ].
So, following code will work as you want.
document.write(appointmentArr[0].start);
document.write(appointmentArr[0].end);

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

Empy array values are created when adding to array

I have the below code:
var changes = new Array();
$(".item_prices").on("blur", function(){
var item_id = $(this).attr("id");
var item_price = $(this).html();
changes[item_id] = item_price;
});
Every time a new value is entered, I want to save the item's ID as the key and its price as the value. If I save items with IDs 4 and 6 and prices 1.99 and 2.99, respectively, I get the following array:
{,,,,1.99,,2.99}
How do I add to the array without incurring empty values?
Use object, not Array:
var changes = {};
The rest is the same.
Key-value should always be saved in an object.
Since you're using jQuery, here is another answer to an unasked question,
Use native javascript functions when it's possible and simple, specially when it's even simpler:
var item_id = $(this).attr("id");
var item_price = $(this).html();
Can and should be:
var item_id = this.id
var item_price = this.innerHTML;
You don't want an array, a simple object will form a collection of key value pairs for you:
var changes = {};
If / when the time comes to enumerate these changes:
for (var name in changes) {
if (changes.hasOwnProperty(name)) {
var value = changes[name];
...
}
}
Arrays are a special case of objects, whose elements have consecutive integer keys. You don't have consecutive keys, so Array is "filling the gaps" for you.
Use a barebones Object instead:
var changes = {};

Javascript JSON stringify No Numeric Index to include in Data

i am trying to pass non numeric index values through JSON but am not getting the data.
var ConditionArray = new Array();
ConditionArray[0] = "1";
ConditionArray[1] = "2";
ConditionArray[2] = "3";
ConditionArray['module'] = "Test";
ConditionArray['table'] = "tab_test";
var Data = JSON.stringify(ConditionArray);
When i alert the Data Variable it has the Values 1,2 and 3 but module and table are not included. How can this be added so that the whole string is passed.
EDIT : And what if i have some multidimensional elements also included like
ConditionArray[0] = new Array();
ConditionArray[0] = "11";
JSON structure only recognizes numeric properties of an Array. Anything else is ignored.
You need an Object structure if you want to mix them.
var ConditionArray = new Object();
This would be an better approach:
var values = {
array : ["1", "2", "3"],
module : "Test",
table : "tab_test"
};
var data = JSON.stringify(values);
Since javascript array accepts numeric index only. If you want non numeric index,use Object instead.
var ConditionArray = {};
ConditionArray[0] = "1";
ConditionArray[1] = "2";
ConditionArray[2] = "3";
ConditionArray['module'] = "Test";
ConditionArray['table'] = "tab_test";
var Data = JSON.stringify(ConditionArray);
Here is the working DEMO : http://jsfiddle.net/cUhha/
According to the algorithm for JSON.stringfy (step 4b), only the (numeric) indices of arrays are stringified.
This is because Array does not contain your elements.
When you do this:
ConditionArray['module'] = "Test";
You actually add a property to the ConditionArray, not elements. While JSON.stringify converts to string only elements of the ConditionArray. For example:
var arr = new Array;
arr['str'] = 'string';
console.log(arr.length) //outputs 0
You need to use an Object instead of Array
If you change the first line to
var ConditionArray = new Object();
you will achieve the desired outcome.
If for some reason you cannot convert your array into object, for instance you are working on a big framework or legacy code that you dont want to touch and your job is only to add som feature which requires JSON API use, you should consider using JSON.stringify(json,function(k,v){}) version of the API.
In the function you can now decide what to do with value of key is of a specific type.
this is the way how I solved this problem
Where tblItemsTypeform is array and arrange is de index of the array
:
let itemsData = [];
for(var i = 0; i <= this.tblItemsTypeform.length -1;i++){
let itemsForms = {
arrange: i,
values: this.tblItemsTypeform[i]
}
itemsData.push(itemsForms)
}
And finally use this in a variable to send to api:
var data = JSON.stringify(itemsData)

javascript how to find number of children in an object

is there a way to find the number of children in a javascript object other than running a loop and using a counter? I can leverage jquery if it will help. I am doing this:
var childScenesObj = [];
var childScenesLen = scenes[sceneID].length; //need to find number of children of scenes[sceneID]. This obviously does not work, as it an object, not an array.
for (childIndex in scenes[sceneID].children) {
childSceneObj = new Object();
childSceneID = scenes[sceneID].children[childIndex];
childSceneNode = scenes[childSceneID];
childSceneObj.name = childSceneNode.name;
childSceneObj.id = childSceneID;
childScenesObj .push(childSceneObj);
}
The following works in ECMAScript5 (Javascript 1.85)
var x = {"1":1, "A":2};
Object.keys(x).length; //outputs 2
If that object is actually an Array, .length will always get you the number of indexes. If you're referring to an object and you want to get the number of attributes/keys in the object, there's no way I know to that other than a counter:
var myArr = [];
alert(myArr.length);// 0
myArr.push('hi');
alert(myArr.length);// 1
var myObj = {};
myObj["color1"] = "red";
myObj["color2"] = "blue";
// only way I know of to get "myObj.length"
var myObjLen = 0;
for(var key in myObj)
myObjLen++;

Categories