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})
Related
var arr = [];
arr['k1'] = 100;
console.log(arr); //o/p - [k1: 100]
arr.length; //o/p - 0
window.copy(arr); //copies: []
I want to convert this array-like object to a proper obj i.e,
arr = { k1: 100}
So doing window.copy(arr) should copy {k1:100}
NOTE- I need to do this as Node.js express server returns empty arrays in response for such cases.
You can use object spread syntax to copy all own enumerable properties from the original object to a new object:
const arr = [];
arr['k1'] = 100;
const obj = { ...arr };
console.log(obj);
This works even if arr is originally an array, rather than a plain object, because the k1 property exists directly on the array.
(But ideally, one should never have code that assigns to arbitrary properties of an array - better to refactor it to use an object in such a situation to begin with)
var array = []
array["k1"] = 100;
var newObject = Object.assign({},array);
console.log(newObject);
Let's say I have an array named derps and then I make an array inside it:
derps[0]=new Array();
how do I get/set data in the newly created array derps[0]?
Simply do this:
derps[0][0] = 'foo';
derps[0][1] = 'bar';
derps[0].push('foobar');
derps[0] = derps[0].concat([5,6,7]);
// Etc, etc.
console.log(derps[0][1]); // 'bar'
console.log(derps[0][2]); // 'foobar'
console.log(derps[0]); // ["foo", "bar", "foobar", "foobar", 5, 6, 7]
Basically, access derps[0] like you'd access any other array, because it is an array.
I'm not going to list All methods you can use on derps[0] ;-)
Also, instead of:
derps[0] = new Array();
You can use the "array literal" notation:
derps[0] = []; // Empty array, or:
derps[0] = ['foo', 'bar', 'foobar']; // <-- With data.
You can create the array with data already in it:
derps[0] = [1, 2, 3];
You can assign values to the array:
derps[0] = new Array();
derps[0][0] = 1;
derps[0][1] = 2;
derps[0][2] = 3;
You can push values to the array:
derps[0] = new Array();
derps[0].push(1);
derps[0].push(2);
derps[0].push(3);
You can push data into the new array:
derps[0].push("some data");
As an aside: you may also use an array literal to create derps[0]:
derps[0] = [];
Easy:
var derps = [];
derps.push([]);
derps[0].push('foo');
derps[0].push('bar');
If you really wish to instantiate the type of the variable before, you can proceed this way (JSFiddle).
var derps = [];
derps[0] = [];
derps[0][0] = "test";
derps[0][1] = "test2";
document.write(derps[0][1]);
Don't forget to write var if you don't want the variable to be global.
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'
};
here's the code
var arr = [1,2,3];
var entry = {};
var test = [];
for(var i=0;i<arr.length;i++){
entry.id = arr[i];
test.push(entry);
}
console.log(test);
i wanna output a array with three different object. but now my objects are all the same, why?
[Object { id=3}, Object { id=3}, Object { id=3}]
The problem is that you're reusing the same object on all of the loop iterations. Create a new entry object within the loop:
var arr = [1,2,3];
var entry; // (modified, don't create here)
var test = [];
for(var i=0;i<arr.length;i++){
entry = {id: arr[i]}; // (modified, create new one here, with `id` prop)
test.push(entry);
}
console.log(test);
Otherwise, if you just assign to entry.id on each loop, you're just changing the id property on the same object. When you push an object reference onto an array, you're just pushing a reference, not copying the object.
You can, of course, do away with the entry variable entirely if you like, but you may want to keep it for clarity, etc. Here's without:
var arr = [1,2,3];
var test = [];
for(var i=0;i<arr.length;i++){
test.push({id: arr[i]});
}
console.log(test);
Somewhat off-topic:
That structure creating an object and simultaneously assigning properties to it is called an object literal. If you had multiple properties, you'd separate their initializers with commas. E.g.:
var obj = {a: 1, b: 2, c: 3};
is the same as
var obj = {};
obj.a = 1;
obj.b = 2;
obj.c = 3;
The values (the right-hand side of the :) can be expressions just as in an assignment statement. The names (the left-hand side of the :) are either literals, as above, or strings:
var obj = {"a": 1, 'b': 2, c: 3};
// ^^^ ^^^ ^---- literal is fine
// | +----------- string (with single quotes) also fine
// +------------------- string (with double quotes) also fine
Off-topic side note: If at some point you find yourself using JSON for data exchange, the rules are similar but slightly more restrictive (JSON is a subset of object literal notation). Specifically, property names must be in double quotes, and all string values (even on the right-hand side) must also be in double quotes.
var arr = [1,2,3];
var test = [];
for(var i=0;i<arr.length;i++){
var entry = {};
entry.id = arr[i];
test.push(entry);
}
console.log(test);
Try that.
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.