How to assign a Javascript array through it's indexes [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Dynamically creating keys in javascript associative array
usually we initialize an array like this:
var ar = ['Hello', 'World'];
And for access to it's values we do:
alert(ar[0]); // Hello
But I want a custom index to assign, ex:
var ar = ['first' => 'Hello', 'second' => 'World'];
and then
alert(ar['first']);
But I can't find how, is there something like this that I could do for assign?
Thank's!

You could use Object instead of Array, you can specify named properties for object
var ar = {
first: 'hello',
second: 'world'
};
alert(ar['first']);
Also you can just assign properties with string keys to your array, this will also work:
var ar = [];
ar['first'] = 'first';
alert(ar['first']);

You need to use an Object.
var obj = {'first': 'hello', 'second': 'world'};
alert(obj.first);

Objects in JavaScript are just property bags (hashtables).
You can:
var ar = {};
ar["name"] = "Dave";
ar["salary"] = "Millions";
alert(ar.name); //Dave
alert(ar["salary"]); //millions
JavaScript allows you to be pretty flexible in how you create these objects.

JavaScript doesn't have associative arrays as such, but object literals:
var obj = {foo:'bar'};
obj.something = 'else';
//or:
obj['foo'] = 'BAR';
JS won't make a fuss if you create named indexes on an array (because the Array object traces back to the Object prototype) but you'll loose all use of Array features (methods like sort, or the magic length property, to name just a few)

just use
var h = new Object(); // or just {}
h['one'] = 1;
h['two'] = 2;
h['three'] = 3;
// show the values stored
for (var k in h) {
// use hasOwnProperty to filter out keys from the Object.prototype
if (h.hasOwnProperty(k)) {
alert('key is: ' + k + ', value is: ' + h[k]);
}
}

You can do this:
var ar = {
'first' :'Hello',
'second' : 'World'
};
As you can see, this is the way you initialize objects in Javascript. Javascript blurs the lines between associative arrays and objects.
You can then access this with:
ar['first']
Or even:
ar.first
Also, you could leave out the quotes in the key initialization, like so:
var ar = {
first :'Hello',
second : 'World'
};

Related

How to create an associative array in JavaScript literal notation

I understand that there are no associative arrays in JavaScript, only objects.
However I can create an array with string keys using bracket notation like this:
var myArray = [];
myArray['a'] = 200;
myArray['b'] = 300;
console.log(myArray); // Prints [a: 200, b: 300]
So I want to do the exact same thing without using bracket notation:
var myNewArray = [a: 200, b: 300]; // I am getting error - Unexpected token:
This does not work either:
var myNewArray = ['a': 200, 'b': 300]; // Same error. Why can I not create?
JavaScript has no associative arrays, just objects. Even JavaScript arrays are basically just objects, just with the special thing that the property names are numbers (0,1,...).
So look at your code first:
var myArray = []; // Creating a new array object
myArray['a'] = 200; // Setting the attribute a to 200
myArray['b'] = 300; // Setting the attribute b to 300
It's important to understand that myArray['a'] = 200; is identical to myArray.a = 200;!
So to start with what you want:
You can't create a JavaScript array and pass no number attributes to it in one statement.
But this is probably not what you need! Probably you just need a JavaScript object, what is basically the same as an associative array, dictionary, or map in other languages: It maps strings to values. And that can be done easily:
var myObj = {a: 200, b: 300};
But it's important to understand that this differs slightly from what you did. myObj instanceof Array will return false, because myObj is not an ancestor from Array in the prototype chain.
You can use Map:
var arr = new Map([
['key1', 'User'],
['key2', 'Guest'],
['key3', 'Admin'],
]);
var res = arr.get('key2');
console.log(res); // The value is 'Guest'
You want to use an object in this case
var myObject = {'a' : 200, 'b' : 300 };
This answer links to a more in-depth explanation: How to do associative array/hashing in JavaScript
Well, you are creating an array, which is in fact an object:
var arr = [];
arr.map;
// function(..)
arr['map'];
// function(..)
arr['a'] = 5;
console.log(arr instanceof Object); // true
You can add fields and functions to arr. It does not "insert" them into the array though (like arr.push(...)).
You can refer to an object fields with the [] syntax.
I achieved this by using objects. Your create an object, and loop through using for in loop. each x will be the index and holder[x] will be the value. an example is below.
var test = {'hello':'world','hello2':'world2'}
for(let x in holder)
{
let inxed = x;
let value = holder[x]
console.log('index ' + x + ' has value of ' + value)
}
Associate array is an array indexed with name similar to an object instead of numbers like in regular array. You can create an associative array in the following way:
var arr = new Array(); // OR var arr = [];
arr['name'] = 'david'
arr['age'] = 23;
console.log(arr['name']);
You can do what you wanted to do this way:
myNewArray = new Array ({'a' : 200, 'b' : 300})

Named objects and collection of them

not sure how to ask tbh :)
I'm used of PHP's associative arrays so much that I struggle to understand how to create an "named array" of objects.
Example:
I have two arrays, two ints and one boolean. This represents one of my entities. I have multiple entities on which I'm doing some work.
In PHP I would write:
$entitites[$entitity_id]['items'][] = $item;
$entitites[$entitity_id]['items_status'][] = $item_status;
$entitites[$entitity_id]['items_count']++;
and so on..
How do I do this with objects in JS?
var entities = {items:[], items_status: [], items_count: 0};
entities[entity_id].items.push(item)
How does one name his object for later access (via name or in my case, entity_id?)
This code doesnt work for me to this extend that my webpage goes blank without any errors produced :S
I also tried this:
var entities = {};
var entity = {items:[], items_status: [], items_count: 0};
but then I dont know how to always add values to already existing object in entities object and how to call that exact object via name eg. entity_id.
Halp :(
Keep entities as an object. Then you can just go ahead and add each entity_id as a key and an object which has all the details of that entity as the value.
var entities = {};
entities["1234"] = {
"items" : [],
"items_status" : [],
"items_count" : 0
};
There are 2 types involved here: Objects & Arrays.
Arrays are simple and you're probably familiar with them from any other language:
var myArray = []; // this is an empty array
myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
// you could also use "var myArray = [1, 2, 3];" instead
alert(myArray[1]); // alerts the value 2
Note: arrays are actually objects, and can have non-index properties as well
You can also use various array functions such as .push(), .pop(), .shift() and so on to mutate the array instead.
Objects share the square brackets notation, but the purpose is different:
var myObject = {}; // this is an empty object
myObject[0] = 1;
myObject[1] = 2;
myObject[2] = 3;
alert(myObject[1]); // alerts the value 2
// but also...
myObject['prop'] = 4;
alert(myObject['prop']); // alerts the value 4
// and
myObject.prop2 = 5;
alert(myObject.prop2); // alerts the value 5
// and lastly
alert(myObject.prop); // alerts the value 4
So while arrays are accessed by index, objects are accessed by property names.
As for your entities, it looks like an array of objects. Lets see how we can do that:
function Entity() {
this.items = [];
this.items_status = [];
this.items_count = 0;
}
var entitites = [];
entities.push(new Entity());
entities[0].items = [1, 2, 3];
entities[0].items_status = ['good', 'good', 'poor'];
entities[0].items_count = 3;
Or you can wrap insertion in a more elegant function:
Entity.prototype.insert(item, status) {
this.items.push(item);
this.items_status.push(status);
this.items_count++;
}
entities[0].insert(4, 'excellent!');
If you want to keep control of the indexes in your JS array you can do so by not using .push() :
var entities = [];
entities[5] = {items:[], items_status:[], items_count:0};
Just replace 5 by your integer entity_id variable, and there you go.
You can use a regular javascript object to create the associative array you're looking for.
Actually it's PHP's implementation that's abit off but all they do is call it different (associative array) to most other language that simply refer to it as an object or hash.
You can use numeric keys in JS and still access them with the [] square brackets.
It works like this:
var my_obj = {};
my_obj[5] = 'any value';
console.log(my_obj); // {5: 'any value'}
JS will not add any redundant undefined to missing indexes either so when looping over the collection you won't loop over undefined.
Also, I can access the object by using the key as a string or as number so you won't have to check if the key is the right type. Taken from the above example:
console.log(my_obj['5']); // 'any value'
console.log(my_obj[5]); // 'any value'
JS Objects are the equivelant of PHP assoc arrays except JS objects are much more flexible than PHP's associative arrays.
The only downside to this is that you can't have duplicate keys.
No two keys may exist that share the same name, in an array if you .push(an_item) it will create a new index making even a duplicate data entry unique but when overwriting a key with a new value only the last value will persist, mind that :)

Can variable in javascript generate variables? [duplicate]

This question already has answers here:
Use dynamic variable names in JavaScript
(19 answers)
Closed 9 years ago.
Let's think about this:
var list = [a1:"123",b2:"234",c3:"345"];
This list obj can create variables by key name like this?
var a1 = list[0];
var b2 = list[1];
var c3 = list[2];
When you use [] notation, you can only create arrays with numeric indexes. To have named properties, you must use {} object notation:
var list = { a1: "123", b2: "234", c3: "345" };
You can then access them as list.a1, list.b2, and list.c3.
The question is not clear. What you show in the example is valid. But you could also create variable names like you suggest like
for( var key in list ) {
window[key] = list[key];
}
This way you will end up having a1, b2 and c3 variables with the desired value, however, these will be globals.
First of all you have a mistake, you are trying to merge hash array and regular array. You should either announce an array like this:
var list = ['123', '234', '345']
and then
var a1 = list[0]
and so on, or announce it like hash array and it will look like this
var list = {'a':'123','b':'234','c':'345'}
var a1 = list.a

Getting Length of Object in Javascript / jQuery

I am trying to set up an array in jQuery and I then need to do a for loop on it. But it seems that I cant use an associative array for some reason?
var items = new Array();
items['foo'] = 123456;
items['bar'] = 789012;
items['baz'] = 345678;
items['bat'] = 901234;
alert(items.length);
This is just a test, but it return 0?
You can't make associative array in JavaScript like what you want, instead you can use Object.
For example:
var items = {
foo : 123456,
bar : 789012,
baz : 345678,
bat : 901234
}
And to calculate the length you can do:
var getObjectSize = function(obj) {
var len = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) len++;
}
return len;
};
Use: getObjectSize(items); // output: 4
For more see here.
Another one is:
Object.keys(items).length;
But not supported by all browsers.
var items = new Array();
items['foo'] = 123456;
The problem lies in the very first line. You believe that you are adding an item to the array at the index foo, but you are actually adding a property to the items variable with a key foo and value 123456. If you were to type items.foo it would give you back your 123456.
The problem with this approach is that adding a property to an array does not magically increase it's length.
If you want to have non-numeric indexes, you need to use an object instead of an array:
var items = {
foo: 123456,
bar: 789012,
baz: 345678,
bat: 901234
};
Another approach might be to set up two different arrays, which you construct in parallel:
var items = [], items2 = [];
items.push('foo');
items2.push(123456);
// etc.
alert(items2.length);​
The efficiency of this approach depends on how you'll use it. If you're only going to loop through the list of items and do something to each of them, this approach may be more efficient. But if you need to use it like an associative array (items['foo']), then you're better off building an object.
The .length property returns the highest numerical index of the array. Thus, in your case, there is no numerical index and it returns 0. Try
items[98] = "something";
items.length will be 98..! Use the .length property with caution, and if you also want to count the non-numerical indici, loop over the Object (an Array is also an Object) and count its ownProperties.

Javascript, jquery - Call array position by using a variable name

I have 2 arrays:
var array1 = [50,60];
var array2 = [120,180];
I am passing a value to a variable like this:
var curId = $(this).attr('id');
I want to set the content of #result to a computation like this:
$(#result).text(number * curId[0]);
Number is a variable predefined by me, and curId[0] shoul actually translate to array1[0] or array2[0], depending on the css class.
Can anyone tell me the right syntax for this? I'm pretty noob at js.
Thanks.
You can use a variable to hold the array that you want to use:
var myArray;
if (something)
myArray = array1;
else
myArray = array2;
$('#result').text(number * myArray[0]);
If you're trying to get the array in a variable from a string containing the name of the variable, you should use an object, like this:
var arrays = {
array1: [50,60],
array2: [120,180]
};
var myArray = arrays[curId];
$('#result').text(number * myArray[0]);
So curId will be the string "array1" or "array2"? Then you'd do it like this:
var lookups = {
array1: [50, 60],
array2: [120,180]
};
var curId = $(this).attr('id');
$('#result').text(number * lookups[curId[0]]);
What that does is create an object (lookups) to contain this information you're looking up. That object has the properties array1 and array1, which are your arrays. You get the string "array1" or "array2" from the ID of your element into the variable curId, and then you use the fact that Javascript lets you look up properties by their name using [] syntax. All of these are the same:
a = lookups.array1;
// is the same as
a = lookups["array1"];
// is the same as
a = lookups["array" + "1"];
// is the same as
s = "array1";
a = lookups[s];
Technically, if your arrays are declared at global scope, you could do that without using the lookups object, but if you're fairly new to Javascript I won't go into why, and regardless, I'd recommend using one.

Categories

Resources