Id like to know if theres a way to programmatically create this array in javascript. Id like to have it dynamic also.
var tblObj = {
main1: {
var2: var3,
var3: var4
},
main2: {
var5: var6
}
};
Thanks
If you mean an object (as in your example), and want to use variables as keys, you'll have to split the declaration in multiple lines, and use bracket notation:
var tblObj = { main1: {}, main2: {} };
tblObj.main1[var2] = var3;
tblObj.main1[var3] = var4;
tblObj.main2[var5] = var6;
(Assuming all those variables are already defined.)
Sure, you can define a multi-dimensional array in one line, exactly as you are, just using the [] array notation. {} is for objects.
var multidim = [
[1,2,3],
[4,5,6],
[7,8,9]
];
Related
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})
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 :)
I have an object var obj = {key1: "value1", key2: "value2"}; I want to add multiple values or array of values to key1 or key2 e.g
var obj = {key1: "arrayOfValues", key2: "value2"}; is it possible? basically I want to send it to php for process.
You can just define an array for the property:
var obj = {key1: ["val1", "val2", "val3"], key2: "value2"};
Or, assign it after the fact:
var obj = {key2: "value2"};
obj.key1 = ["val1", "val2", "val3"];
You can make objects in two ways.
Dot notation
Bracket notation
Also you can be define values in array with/without initial size.
For scenario one you can do the following in worst case scenario:
var obj = {}
obj.key1 = new Array();
obj.key2 = new Array();
// some codes related to your program
obj.key1.push(value1);
// codes ....
obj.key1.push(value);
// ... same for the rest of values that you want to add to key1 and other key-values
If you want to repeat the above codes in bracket notation, it will be like this
var obj = {}
obj['key1'] = new Array();
obj['key2'] = new Array();
// some codes related to your program
obj['key1'].push(value1);
// codes ....
obj['key1'].push(value);
// ... same for the rest of values that you want to add to key1 and other key-values
With bracket notation, you can use characters e.g 1,3,%, etc. that can't be used with dot notation.
I came across same scenario and after scanning through many resources I found very elegant solution. Using Bracket Notation one can add multiple values to same key
let obj = {}
const demo = (str, objToAdd) => {
if(!obj[str]){
obj[str] = {}
}
const key = Object.keys(objToAdd)[0]
obj[str][key] = Object.values(objToAdd)[0]
}
Here important line is obj[str][key] = Object.values(objToAdd)[0]. This line will help you create object inside same key. obj[str][key] will create object inside object.
to add values call function as below
demo('first', {content: 'content1' } )
demo('first', {content2: 'content3' } )
obj
first: {content: "content1", content2: "content3"}
Hopefully this will help someone.
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'
};
I currently have a problem in deleting entries from an associative array in JS.
I tried this:
myArray['key'] = value;
myArray['key1'] = value1;
...
delete myArray['key'];
But I get following results in my application:
[ undefined, { key1: 'value1', key2: 'value2' }, undefined,
{ key1: 'value1', key2: 'value2' }, undefined, undefined ]
How can I delete the whole entry, key and value? I found the method splice() but I think it uses a different index. I wasn't able to delete the entries I want by passing the key to splice().
It seems you are mixing arrays and objects. Associative arrays should be realized with objects:
myArray = {};
myArray['key'] = value;
myArray['key1'] = value1;
It is a bit confusing though because in your output, the objects don't have key anymore (so it worked), but the array containing those objects as undefined values. I cannot see how
delete myArray['key']; is related to your output and which variable now contains which value (please clarify).
But it looks like you did something like:
var container = new Array(6);
container[1] = myArray;
container[3] = myArray;
This will initialize the array with 6 undefined values (sort of) and then set the second and forth value to something else.
If you want to use that "array" as associative array, you should declare it as object too:
var container = {};
Please post more code if you need a better answer.
Update: Yes, you should declare displayedWidgets as object:
var widgets = {
displayedWidgets: {},
clear: function() {
this.displayedWidgets = {};
},
add: function(widget) {
this.displayedWidgets[widget.id] = widget;
},
addArray: function(newWidgets) {
// note that `each` is only available in newer browsers,
// just loop over the array
for(var i = newWidgets.length; i--; ) {
this.add(newWidgets[i]);
}
},
remove: function(widgetId) {
if (widgetId in this.displayedWidgets) {
delete this.displayedWidgets[widgetId];
}
}
};