I have an autocomplete text box that users can type an item code into and need to find out what the id number of that item code is in javascript.
An associative array is the way I would imagine it should be done, but the following seems a little long winded and I'm hoping someone has a better way to do it or shorthand of what I have below:
var itemIds = new Array();
itemIds["item1"] = 15;
itemIds["item2"] = 40;
itemIds["item3"] = 72;
...
function getItemId(code){
return itemIds[code];
}
What you're doing isn't an array - it's an object (objects in JavaScript are the equivalent-ish of associative arrays in PHP).
You can use JavaScript object literal syntax:
var itemIds = {
item1: 15,
item2: 40,
item3: 72
};
JavaScript object members can be accessed via dot notation or array subscript, like so:
itemIds.item1;
itemIds['item1'];
You'll need to use the second option if you've got the member name as a string.
Try using Object Literal notation to specify your lookup like this:
var itemIds = {
"item1" : 15,
"item2" : 40
...
};
Access should still work like this:
var item1Value = itemIds["item1"];
Related
I have a huge object that contains the entire ESV Bible. I am trying to get a random book of the Bible whenever I press a button. Here is a small sample of the object.
var esvObject = {
"Genesis": {
"1": {}
"2": {}
"3": {}
},
"Exodus": {
"1": {}
"2": {}
"3": {}
}
}
Here is the code that I am using to get a random book.
var randNum = Math.floor(Math.random() * 66);
var randBook = esvObject[randNum];
var output = randBook;
I would expect this to work, but the output I always get is "undefined," where as I would like the output to be "Genesis" or "Exodus" etc. Getting the random number works, but if
randNum = 1
then
randBook = esvObject[1]
the output returns as "undefined" and I don't know why.
Well the reason you get undefined is that your object is of the structure:
let esvObject = {
bookName: {
1 : {}
}
}
Using bracket [] notation on a javascript object finds the matching key for the name and returns it's value. In your top level object (the one with bookNames for keys), you have to use a valid book name like Genesis. To do so, leverage the Object.keys function of javascript to get an array of all the keys in your object.
You can then use [] notation, which has a different semantic on arrays.
let books = Object.keys(esvObject); // ["Genesis", "Exodus", ...]
let randomKey = books[randNum] // this is an array, so index access works
let book = esvObject[randomKey] // matches on the bookname
And to tie it all together, esvObject["Genesis"][1] would have been valid because the object stored as "Genesis" has a property 1
You are generating random number. And then trying to pick property using that number.
But you object has properties Genesis and Exodus not 1 or 20 etc.
What you need to do is Object.getOwnPropertyNames(esvObject)
that will give you array of the property names. In this case ['Genesis', 'Exodus'] and then you need to pick random element from that array
It would not work because it does not know that the first book is named "Genesis".
To be able to use numbers from the random function you will need to use array from the keys of the object
var keys = esvObject.keys( obj );
randBookKey = keys[randNum]
randBook = esvObject[randBookKey]
esvObject (as you show it) does not have any integer keys. So you need to select a random (existing) key instead:
esvObject[Object.keys(esvObjects)[Math.floor(Math.random() * 66)]]
You're confusing accessing an array with accessing an object.
An array:
arr = ["genesis", "exodus"]
is accessed like this:
arr[0] // genesis
An object:
obj = { "genesis" : "foo", "exodus" : "bar"}
is accessed like this:
obj["genesis"] // foo
To achieve what you want to do, see Access non-numeric Object properties by index?
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;
Assuming an object is initialized as following:
var myObj = {
"key1":"val1",
"key2":"val2",
"key3":"val3",
...
};
Can I retrieve key values like this?
var retrKey1 = myObj[0];
var retrKey2 = myObj[1];
var retrKey3 = myObj[2];
...
The issue I am trying to solve is that I need to pick random key values from this object. Generating a random number is not an issue, but:
How can I retrieve the number of keys in the object/map?
Can I retrieve the key values using a integer index like in arrays?
If not, what are my options?
The Object.keys method returns an array of object properties. You can index the array with numbers then.
var myObj = {
"key1":"val1",
"key2":"val2",
"key3":"val3",
...
};
var keys = Object.keys(myObj);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
No, because there's no ordering among property keys. If you want ordered keys, you need to work with an array.
You could define a structure like this :
var myObj = [
{key:"key1", val:"val1"},
...
];
I am trying to create an array in javascript which will allow me to access data like this:
var name = infArray[0]['name'];
however I cant seem to get anything to work in this way. When i passed out a assoc array from php to javascript using json_encode it structured the data in this way.
The reason why i have done this is so i can pass back the data in the same format to php to execute an update sql request.
JavaScript doesn't have associative arrays. It has (numeric) arrays and objects.
What you want is a mix of both. Something like this:
var infArray = [{
name: 'Test',
hash: 'abc'
}, {
name: 'something',
hash: 'xyz'
}];
Then you can access it like you show:
var name = infArray[0]['name']; // 'test'
or using dot notation:
var name = infArray[0].name; // 'test'
simply var infArray = [{name: 'John'}, {name: 'Greg'}] ;-)
JavaScript doesn't have assoc arrays. Anything to any object declared as obj['somthing'] is equal to obj.something - and it is a property. Moreover in arrays it can be a bit misleading, so any added property won't changed array set try obj.length.
JavaScript do not have 2D associative array as such. But 2d associative array can be realized through below code:
var myArr = { K1: {
K11: 'K11 val',
K12: 'K12 Val'
},
K2: {
K21: 'K21 Val',
K22: 'K22 Val'
}
};
alert(myArr['K1']['K11']);
alert(myArr['K1']['K12']);
alert(myArr['K2']['K21']);
alert(myArr['K2']['K22']);
I know to add a named object to an existing JavaScript object you do this:
var json = {};
json.a = {name:"a"};
But how can you add an object to an existing JavaScript object in a similar fashion without assigning it an associative name, so that it could be accessed by a for() statement. Sorry if I'm being a little vague, I don't know a lot about JavaScript objects.
UPDATE:
I want the end result to look like this:
var json = [{name:'a'}{name:'b'}];
What you have there is not strictly a JSON object. You're using JS object literals rather.
You can do this:
var jsObj = {};
// add a 'name' property
jsObj = { name: 'a'};
var anotherObj = { other: "b" };
// will add 'other' proprty to jsObj
$.extend(jsObj, anotherObj);
// jsObj becomes - {name: 'a', other:'b'}
The JSON representation of above will look like:
var jsonString = "{'name': 'a', 'other':'b'}";
// will give you back jsObj.
var jsonObj = JSON.Parse(jsonString); // eval(jsonString) in older browsers
Note that you cannot have property without a name. This is not valid:
// invalid, will throw error
jsObj = { : 'a'};
Try an array that you push an item on to using
myArrayVar.push(value);
or
myArrayVar[myArrayVar.length] = value;
It makes no sense to have a property of an object without a property name. A "for ... in" loop is a loop over that collection of property names, after all. That is,
for (var k in obj)
will set "k" equal to each of the names of properties in "obj" in turn.
You cannot do this, because a JSON object is a collection of string-value pairs. A value can be an array, and you can push your object into that array, without an associative name.
http://www.json.org/
What you are describing is an array of objects.
var j = [{name:'a'},{name:'b'}];
This has the properties you are looking for. You can operate on it like so:
for(var i in j) {
alert(j[i].name);
}