Unable to get the length of an array - javascript

I am using an array as defined below
cat_id = Object { 2="text", 3="TKL1", -1="Select an Attribute"}.
when i am trying to retrieve the length of "cat_id" as
var l = cat_id.length;
its showing the length as "undefined".
But, I am unable to get the length of "cat_id". I am unable to use replace(), indexOf() and split() functions.
for example:
var index = cat_attr.indexOf(",")
Its showing error as below:
TypeError: cat_attr.indexOf is not a function

This isn't array, this is Object. Array defined in this way: [1,2,3]. If you want retrieve the "length" of object you can do this in this way:
var students = {job:92, adam:67,sara:83};
var studentNames = Object.keys(students);
var studentsLength = studentNames.length;
If you want split object to array you can do this in this way:
var students = {jon:92, adam:67,sara:83};
var studentNames = Object.keys(students);
var studentArray = studentNames.map(function(name){
var student = {};
student.name = name;
student.grade = students[name];
return (student);
}); // [{name:jon,grade:92},{name:adam,grade:67},{name:sara,grade:83}]

cat_id variable you defined as not an array, it is a javascript object. That is why it is not behaving like array! [] is the array notation. Use array notation [] instead of {} object notation you have used.

Your problem is wrong type and wrong syntax.
In your question your cat_id is an Object, not string or array. So you can not call length() or indexOf() funtion.
Moreover, you typed wrong syntax, it should be:
var cat_id = { 2: 'text', 3: 'TKL1', -1: 'Select an Attribute'}.

Here is how to retrieve property count (size and/or length)
size_obj = Object.keys(my_object).length;
As in
size_cat_id = Object.keys(cat_id).length;

Related

JSON stringify does not convert array [duplicate]

In the example below, the array2.length is only 10, while in my mind, it should be 13.
Why does the "string keyed" indexes not increase the length of the array?
I can store things and still access it, and the VS debugger shows that those arrays are being stored properly. So why is the length not increased?
var array2 = new Array();
array2["a"] = new Array();
array2["b"] = new Array();
array2["c"] = new Array();
for (var i = 0; i < 10; ++i)
array2[i] = new Array();
var nothing = "";
for (var i = 0; i < array2.length; ++i)
nothing = "";
Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object. These are equivalent:
array.a = 'foo';
array['a'] = 'foo';
Those properties are not part of the "data storage" of the array.
If you want "associative arrays", you need to use an object:
var obj = {};
obj['a'] = 'foo';
Maybe the simplest visualization is using the literal notation instead of new Array:
// numerically indexed Array
var array = ['foo', 'bar', 'baz'];
// associative Object
var dict = { foo : 42, bar : 'baz' };
Because the length is defined to be one plus the largest numeric index in the array.
var xs = [];
xs[10] = 17;
console.log( xs.length ); //11
For this reason, you should only use arrays for storing things indexed by numbers, using plain objects instead if you want to use strings as keys. Also, as a sidenote, it is a better practice to use literals like [] or {} instead of new Array and new Object.
You're not adding items to the array; you're adding properties to the Array object.
As said above, use object for associative arrays.
If you don't you won't necessarily notice you're doing it wrong, until you innocently use "length" as an array index :
var myArray = [];
myArray["foo"] = "bar"; //works
console.log(myArray["foo"]) //print "bar"
myArray["length"] = "baz" //crash with a "RangeError: Invalid array length"
That is because you are replacing the length attribute of an array with a String, which is invalid.
"string keyed" indexes are not indexes at all, but properties. array2["a"] is the same as saying array2.a. Remember that you can set properties on any kind of variable in javascript, which is exactly what you're doing here.
You can push object to array, it will automatically get indexed (integer). If you want to add index as you want then you want to make it as object
If you want to use an object's properties as if they were like instances of a string indexed array, the work around for the length is:
var myArray = new Array();
myArray["a"] = 'foo';
myArray["b"] = 'bar';
myArray["c"] = 'baz';
let theLength = Object.keys(myArray).length

jQuery HashMap Implementation: Missing : after Property ID Error

I'm trying to dynamically populate a HashMap in jQuery, and am following this example: https://stackoverflow.com/a/4247012/1005607 Orig Question: How to create a simple map using JavaScript/JQuery
I need to add a hash entry where the key comes from an array item, and the value is a variable. But I'm getting an error. What's wrong? This should be equivalent to populating "item2" -> 2 in the HashMap. I would be able to get 2 by invoking laneMap.get("item2").
var laneMap = {};
var eventIDs = [];
eventIDs.push('item1');
eventIDs.push('item2');
var currlane = 2;
laneMap.push({eventIDs[1] : currlane });
You can't add key/value pair using push. There are two ways of doing it
Using dot notation:
obj.key3 = "value3";
Using square bracket notation:
obj["key3"] = "value3";
var laneMap = {};
var eventIDs = [];
eventIDs.push('item1');
eventIDs.push('item2');
var currlane = 2;
laneMap.key = currlane-1;
laneMap[eventIDs[1]] = currlane ;
console.log(laneMap);
P.S.- You can't use [] in dot notation
You can only use .push with an array. Here's how to assign a dynamic object property:
laneMap[eventIDs[1]] = currlane;

variable values to store a array

how can I variable values to store a array?
Look my code:
var collection =normal,user,student ;
var array = [collection];
alert(array[0]);
In this case, alert would popup a normal,user,student. but i need an array such as array[0] get normal,array[1] get user,array[2] get student like that
how it is possible
Is there any chance to convert such variable into a JS array?
As normal,user,student are values. You can use split() to split the string using , as deliminator then indexes can be used to access elements.
var collection = "normal,user,student";
var array = collection.split(',');
console.log(array[0]);
There are many, many ways to create arrays ... some examples:
// just declare an array directly
var array1 = ["normal", "user", "student"];
console.log(array1[0]);
// use split to create an array out of a string
var collection = "normal,user,student";
var array2 = collection.split(",");
console.log(array2[1]);
// use split and map to create an array by your needs
var collection = " normal, user , student ";
var array3 = collection.split(",").map(function(value) {
return value.trim();
});
console.log(array3[2]);
// push each value to the array
var array4 = [];
array4.push("normal");
array4.push("user");
array4.push("student");
console.log(array4[0]);
// ...
var collection = "normal,user,student";
var jsarray = collection.split(",");
alert(jsarray[0]);
alert(jsarray[1]);
alert(jsarray[2]);
Are you trying to add the existing variables to the array? If so you are just missing your square brackets:
var collection = [normal, user, student];
If you would like the elements to contain the string values, you would do it like this:
var collection = ["normal", "user", "student"];

Javascript add data in multidimesional array

I'm trying to understand how to add a value into my array. It is multidimensional:
var eventcontent = {
'2015-05-02' : [{'title':'somethingtitle1','content':'somethingcontent1','something':'something1'},{'title':'somethingtitle2','content':'somethingcontent2','something':'something2'}],
'2015-05-07' : [{'title':'somethingtitle7','content':'somethingcontent7','something':'something7'}],
}
How can I achieve adding the following data into the '2015-05-02'?
{'title':'somethingtitle3','content':'somethingcontent3','something':'something3'}
thanks for your help
eventcontent is object. Firstly you have to gain access to array stored under 2015-05-02 key. 2015-05-02 is not valid property identifier so you can't access it via
var array = eventcontent.2015-05-02 // SyntaxError
instead you have to use bracket notation
var array = eventcontent['2015-05-02'];
then you can for example push your data to the array
var data = {'title':'somethingtitle3','content':'somethingcontent3','something':'something3'};
var array = eventcontent['2015-05-02'];
array.push(data);
Edit:
Probably you should also check if array actually exist so your code becomes:
var data = {'title':'somethingtitle3','content':'somethingcontent3','something':'something3'};
var array = eventcontent['2015-05-02'];
if (array === undefined) // check if it is undefined and if so...
array = eventcontent['2015-05-02'] = []; // make empty array and assign it to eventcontent under '2015-05-02' key
}
array.push(data);

Why does a string index in an array not increase the 'length'?

In the example below, the array2.length is only 10, while in my mind, it should be 13.
Why does the "string keyed" indexes not increase the length of the array?
I can store things and still access it, and the VS debugger shows that those arrays are being stored properly. So why is the length not increased?
var array2 = new Array();
array2["a"] = new Array();
array2["b"] = new Array();
array2["c"] = new Array();
for (var i = 0; i < 10; ++i)
array2[i] = new Array();
var nothing = "";
for (var i = 0; i < array2.length; ++i)
nothing = "";
Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object. These are equivalent:
array.a = 'foo';
array['a'] = 'foo';
Those properties are not part of the "data storage" of the array.
If you want "associative arrays", you need to use an object:
var obj = {};
obj['a'] = 'foo';
Maybe the simplest visualization is using the literal notation instead of new Array:
// numerically indexed Array
var array = ['foo', 'bar', 'baz'];
// associative Object
var dict = { foo : 42, bar : 'baz' };
Because the length is defined to be one plus the largest numeric index in the array.
var xs = [];
xs[10] = 17;
console.log( xs.length ); //11
For this reason, you should only use arrays for storing things indexed by numbers, using plain objects instead if you want to use strings as keys. Also, as a sidenote, it is a better practice to use literals like [] or {} instead of new Array and new Object.
You're not adding items to the array; you're adding properties to the Array object.
As said above, use object for associative arrays.
If you don't you won't necessarily notice you're doing it wrong, until you innocently use "length" as an array index :
var myArray = [];
myArray["foo"] = "bar"; //works
console.log(myArray["foo"]) //print "bar"
myArray["length"] = "baz" //crash with a "RangeError: Invalid array length"
That is because you are replacing the length attribute of an array with a String, which is invalid.
"string keyed" indexes are not indexes at all, but properties. array2["a"] is the same as saying array2.a. Remember that you can set properties on any kind of variable in javascript, which is exactly what you're doing here.
You can push object to array, it will automatically get indexed (integer). If you want to add index as you want then you want to make it as object
If you want to use an object's properties as if they were like instances of a string indexed array, the work around for the length is:
var myArray = new Array();
myArray["a"] = 'foo';
myArray["b"] = 'bar';
myArray["c"] = 'baz';
let theLength = Object.keys(myArray).length

Categories