I want to use a variable as index of my associative array
var usersName = []; // Just defining
userName[socket.id] = socket.name; // socket.id is an alphanumeric string
I want to use that socket.id(string) as the custom index of usersName array, so I can get a list of all the users connected to the socket. The problem is the way I'm escaping the variable ( I guess).
I've tried this but didn't work:
usersName ['\''+socket.id+'\''] = socket.name;
This works in PHP but, I just can't get it to work in javascript
Thanks for the help.
What you are trying to do is essentially this:
// say socket = {id: 123, name: 'Bob'};
var foo = {}; // create an object
foo[socket.id] = socket.name; // put socket.name under foo.
var i;
for (i in foo) { //loop through list
console.log(i, "is", foo[i]); //123 is Bob
}
right? Like the comments posted, JS doesn't have "associative arrays" but instead something better- psuedo-classical objects. Objects in JavaScript are nothing like those in PHP. You need to relearn what an "object" means when learning JavaScript. Arrays in javascript are not something to be proud of.. They are essentially just objects extending the Array prototype and with a special 'length' property. Arrays in JS also allow you to get data in order, by performing a for(i =..; i..; i +=..) loop. Other than the benefits of Array.prototype and the ability to load a list of things in some reliable order, arrays are not that special.
Hopefully this will work the way you want it. It's kind of PHP style:
1
var usersName = new Object();
usersName["123"] = 'Jane';
usersName["923"] = 'Charles';
for (var key in usersName) {
console.log(key + ' => ' + usersName[key]);
}
2
var usersName = {
'123' : 'Jane',
'923' : 'Charles'
};
for (var key in usersName) {
console.log(key + ' => ' + usersName[key]);
}
Related
I am trying to create a function that generates empty arrays.
Problems:
I don't know how to show the name of the array in console.log.
how to make the array and array's name accessible in a global scope
function arrayCreator (arrName){
arrName = [];
console.log(arrName.name() + ' : ' arrName);
}
P.S. arrName.name() doesn't work, of course. It is more like a placeholder.
This is one possible implementation that may achieve the result you want. The function stores the arrays in an object. You can access the array names on a global scope using Object.keys(myobject) . Of course I just made a loop to create some random array names and call the function multiple times. I'm not sure how your application will be getting array names.
var arrObject = {};
function arrayCreator (arrName){
arrObject[arrName] = [];
}
for( i = 0; i < 10; i++)
{
arrayName = "myArray" + i;
arrayCreator(arrayName);
}
console.log(arrObject);
console.log(Object.keys(arrObject));
I've created my array as following:
var test = [];
test['pizza'] = 4;
test['pudding'] = 6;
I'm used to use $.each to loop over my array and print out the values and indexes. I'm doing this as following:
$.each(test, function (index, value){
console.log(value);
});
Yet somehow it does only print [].
How would one loop through an array as mine to print out the values 4 and 6?
each will only iterate over iterable properties of the array, pizza and pudding are not iterable properties.
As you require the key-value pair, declare the variable as object.
var test = {};
test['pizza'] = 4;
test['pudding'] = 6;
You don't need jQuery to iterate through a Javascript array, just use for.
var test = [];
test['pizza'] = 4;
test['pudding'] = 6;
for (var k in test) {
if (test.hasOwnProperty(k)) {
console.log('Key: ' + k + ' Value: ' + test[k]);
}
}
// Key: pizza Value: 4
// Key: pudding Value: 6
You don't need to declare test as an object for this (suggested in other answers), array is fine.
By using for you are improving performance of your application. See here.
In both Firefox and Chrome, the for loop is well over 100x faster than
the others.
you might want to choose what happens to serve your needs. I guess you were trying to get a array of objects which will look something like [{},{},{},{}]
Here test is an object(Associative array), not an array so you need to declare it as javascript object
var test = {};
test['pizza'] = 4;
test['pudding'] = 6;
$.each(test, function (index, value){
console.log(value);
});
How do you sort an object by keys based on another array in Javascript?
This is the same question as here PHP Sort an Array by keys based on another Array?
But I need the same process for Javascript.
Thanks
The JavaScript specification does not require that object keys maintain their order, so it is not safe to attempt to sort them. It is up to each environment to implement the standard, and each browser does this differently. I believe most modern browsers will sort keys on a first-in-first-out basis, but since it is not part of the standard, it is not safe to trust this in production code. It may also break in older browsers. Your best bet is to place your object keys into an array, sort that array and then access the values of the object by the sorted keys.
var myObject = { d: 3, b: 1, a: 0, c: 2 },
sortedKeys = Object.getOwnPropertyNames(myObject).sort();
You could then map the ordered values into a new array if you need that.
var orderedValues = sortedKeys.map(function (key) { return myObject[key]; });
As QED2000 pointed out, even if you create a new object, there's no guaranty that the properties will remain in a specific order. However you can sort the keys depending on a different array.
<script>
function sortArrayByArray(a, b)
{
return order.indexOf(a) - order.indexOf(b);
}
var order = new Array('name', 'dob', 'address');
var customer = new Array();
customer['address'] = '123 fake st';
customer['name'] = 'Tim';
customer['dob'] = '12/08/1986';
customer['dontSortMe'] = 'this value doesnt need to be sorted';
var orderedKeys = Object.keys(customer).sort(sortArrayByArray);
orderedKeys.forEach(function (key) {
document.write(key + "=" + customer[key] + "<br/>");
});
</script>
The output is
dontSortMe=this value doesnt need to be sorted
name=Tim
dob=12/08/1986
address=123 fake st
I am creating javascript two dimensional array
code is :
var field_arr=[];
$(".dr").each(function(index){
Id=$(this).attr("id");
alert(dragId);
topPos=$("#"+ dragId).position().top;
left=$("#"+ dragId).position().left;
parentDiv=$("#"+dragId).parent().attr("id");
parentDiv= parentDiv.split('-');
paId=parentDiv[1];
field_arr[Id]=new Array();
field_arr[Id]['paId']=paId;
field_arr[Id]['top']=topPos;
field_arr[Id]['left']=left;
});
console.log(field_arr);
Output Is:
[undefined, [] left 140 paId "1" top 10
What is problem in It Any help Should be appreciated.
The problem is in the display method of your arrays. The information is there, but both alert and console.log will not show it to you because it is expected that the only interesting properties of arrays are the ones with numeric indexes.
In JavaScript, unlike PHP, objects are used as maps/associative arrays.
First to check that your information is actually there:
$(".dr").each(function(index){
var Id=$(this).attr("id");
console.log(Id, field_arr[Id]['paId'], field_arr[Id]['top'], field_arr[Id]['left']);
});
Now to make make the display methods work you can go about multiple ways, but the best one is to use objects instead:
var field_arr = Object.create(null); // replace with {} if you want to support IE8-
$(".dr").each(function(index){
var id = $(this).attr("id"); // added var to keep variable local
var drag = $("#"+dragId);
field_arr[id] = Object.create(null); // {}
field_arr[id]['paId'] = drag.parent().attr("id").split('-')[1];
field_arr[id]['top'] = drag.position().top;
field_arr[id]['left'] = drag.position().left;
});
console.log(field_arr);
Iterating over properties of objects is quite easy:
for (var id in field_arr) {
console.log(field_arr[id], field_arr[id]['paId'], 'etc');
}
Add a hasOwnProperty check if your object doesn't inherit from null (var obj = {} needs it, unlike var obj = Object.create(null))
you're storing values with a key string and its wrong because you declared your field_arr as a numerical array (well there's no such thing as associative array in javascript i think).
field_arr[Id] = new Array();
field_arr[Id]['paId']=paId; //this is wrong
You need to create an object to store in values as if they are associated with string keys. But literally they are object properties
redeclare it like this
field_arr[Id] = {}; //you create an object
field_arr[Id]['paId'] = paId; //create an object property named paId and store a value
field_arr[Id].paId = paId; //you can also access property paId like this
EDIT:
but to conform to you current code you can access your indexes using strings by accessing it like a property of an object. (Thanks to Tibos)
var field_arr=[];
...
...
field_arr[Id].paId = paId;
This should be pretty easy but I'm a little confused here. I want to fill this object:
var obj = { 2:some1, 14:some2, three:some3, XX:some4, five:some5 };
but in the start I have this:
var obj = {};
I´m making a for but I don't know how to add, I was using push(), but is not working. Any help?
You can't .push() into a javascript OBJECT, since it uses custom keys instead of index. The way of doing this is pretty much like this:
var obj = {};
for (var k = 0; k<10; k++) {
obj['customkey'+k] = 'some'+k;
}
This would return:
obj {
customkey0 : 'some0',
customkey1 : 'some1',
customkey2 : 'some2',
...
}
Keep in mind, an array: ['some1','some2'] is basicly like and object:
{
0 : 'some1',
1 : 'some2'
}
Where an object replaces the "index" (0,1,etc) by a STRING key.
Hope this helps.
push() is for use in arrays, but you're creating a object.
You can add properties to an object in a few different ways:
obj.one = some1;
or
obj['one'] = some1;
I would write a simple function like this:
function pushVal(obj, value) {
var index = Object.size(obj);
//index is modified to be a string.
obj[index] = value;
}
Then in your code, when you want to add values to an object you can simply call:
for(var i=0; i<someArray.length; i++) {
pushVal(obj, someArray[i]);
}
For info on the size function I used, see here. Note, it is possible to use the index from the for loop, however, if you wanted to add multiple arrays to this one object, my method prevents conflicting indices.
EDIT
Seeing that you changed your keys in your questions example, in order to create the object, you can use the following:
function pushVal(obj, value, key) {
//index is modified to be a string.
obj[key] = value;
}
or
obj[key] = value;
I'm not sure how you determine your key value, so without that information, I can't write a solution to recreate the object, (as is, they appear random).