Javascript Array Key Retrieval - javascript

My JavaScript code stores a lot of data in arrays. I want to retrieve a key using something similar to what I wrote below. It key that should be retrieved is based on variables that are page-dependent . The following code doesn't work. Can anyone give me a solution to this problem?
This is part of a script that does automatic conjugation. (looks for SUBJECT in a div and then looks for VERB in another div and then conjugates the verb by retrieving the conjugated form from the array)
function getarray(Array,Key) {
return Array[Key];
}
Example of how it should work:
verb = innerhtmlfromdiv;
subject = innerhtmlfromotherdiv;
function getarray(Array,Key) {
return Array[Key]; }
conjugatedverb = getarray(verb,subject);
htmltextbox.value = conjugatedverb;

First off, what you want is an Object, not an Array. I'm guessing that you're new to javascript and your previous language was either PHP or PERL, and so you think what you're using is an "Associative Array".
The basics: There is no such thing as Associative arrays in Javascript. There is Objects, and a non-primitive subclass of Object called Array, which has some methods for dealing with Numericly named object properties, and a magic length property.
Since the keys you are dealing with are strings, not numbers, you have no use for Arrays.
Javascript Objects on the other hand are similar to an Associative array in php, or a hash in perl. (but they are not exactly the same thing).
As you have no doubt discovered, with an Object, you can use subscript notation to access certain properties, as in
verbs["go"] = "went";
this is equivilent to
verbs.go = "went";
a common mistake is to think that the dot notation is only used for objects, and the subscript notation for "associative arrays", because this is how it works in PHP. In javascript the two notations are interchangable. Since Arrays are a subclass of Object, the above examples work on them as well (but they don't use any special properties of Arrays).
As for your specific problem:
You need an object full of objects.
so for instance
var verbs = {
"do":{"Truck":"Drive","Blender":"Turn On","Bike":"Ride"},
"take":{"Money":"Steal","Julie":"Accompany","Lever":"Pull}
}
then your function would be:
function conjugate (verb, subject) {
return verbs[verb][subject];
}
and an example of its use would be
conjugate("do","Truck") // returns "Drive"

Try changing the parameter name Array to something else. Array is the name of a built-in function/object in javascript.

I don't quite get the point of the function. This is like writing:
function getValue(var) {return var}
Why not just get the value the normal way without wrapping it in a useless function:
conjugatedverb = verb[subject];
htmltextbox.value = conjugatedverb;
Also, your code doesn't make sense when you claim to do an innerHTML from an element and somehow get an object instead of a string. What is really going on? I think your problem starts even before this snippet of code.

Related

JavaScript Object Syntax & Notation

I've been using JavaScript for a short period of time, and have found myself interested as to whether or not there is any correlation between the . syntax used for referencing children of an object, and functions such as console.log.
And was interested whether functions such as this, were in a way objects behind the scenes, with log being a method inside of a console object, and if I am just referencing the child of an object.
Or another example, the .length method, is this just a hidden property of the object or array you are referencing.
Apologies if this is poorly worded, I was struggling to write down my train of thought, and I would be incredible appreciative if anyone could let me know if this is how methods such as these are structured, or if I am thinking of them in completely the wrong way.
Notice how you can access the length property on a string. While string is a primitive, the length property actually exits on a wrapper object that is created temporarily when we try to read .length.
Arrays and other collections have this property, because they are objects themselves.
Hope this helps to clarify a bit!
console.log is not a function, per se. The function is the log property on the console object. console is an object with many methods:
To access it's method, just like to access any property of a JS object, you can use dot notation or square bracket notation
var log = console.log;
log('hello');
var logSquare = console['log'];
logSquare('hello');
// or just do
console['log']('hello');
Except for primitives, everything in JS is an object.

Use string variable to access value of object

I have a text input.
I want the user to be able to fill out a value in that text input like some of these examples:
results[0].address_components[0].long_name
results[0].formatted_address
fo.o[0].bar (where fo.o is a single key)
etc. (pretty much literally anything)
Then I want to take that value and use it as a key on some parsed JSON. So like...
$.parseJSON('data.json').results[0].address_components[0].long_name would return something like San Francisco.
How can I do this?
If I save the input value as a variable, say selector, and then try $.parseJSON('data.json')[selector] it just comes back undefined.
If I try to regex the selector and convert all instances of [ into . and remove all ] and split at . then reduce, then selectors like fo.o (one key) will break...
Thanks in advance!
You should generally set the results of parseJSON to a variable, rather than parse it every time you access it. parseJSON is generally going to go down to C code (depending on the environment), but it will still be really inefficient to call it over and over.
var res = $.parseJSON('data.json');
From there, you can access it like you would any other JavaScript object:
res.results, which is identical to res["results"] (which, in your case appears to be some kind of array).
A string key with special characters (., -, and pretty much anything non a-zA-Z0-9) is always accessed via the second form: res["fo.o"].
Note that this chains, so you can access res["fo.o"]["bar"] exactly as you'd address res["fo.o"].bar.
I would recommend using a JavaScript library like lodash for this (if this is feasible in your project, otherwise looking at its implementation might help):
It provides a large set of utility functions. The get function does exactly what you are looking for, namely it resolves a path on an object.
Sample code (assuming _ is your lodash reference):
var path = 'results[0].address_components[0].long_name'; // the user input
var data = $.parse('data.json');
var result = _.get(data, path); // resolves the path on the data object
As for the fo.o property name, I doubt there would be an easy solution, as this essentially makes your syntax ambiguous. How would you distinguish between a property fo.o and fo?
use eval. You would put everything as a string. So just concatenate strings based on the input. Then eval it. for example:
var str = "$.parseJSON('data.json').results[0].address_components[0].long_name";
and then eval it at runtime.
var result = eval(str);

Javascript - How to create an object array?

I want to know if it is possible to declare an array in Javascript of the type "com.peregrine.servicecenter.PWS.Common.MessageType". In java it is easy but in javascript I have not idea. Thanks.
sure it's possible:
var myArray = [];
remember that javascript is not a statically typed language, so you don't need to declare an array of a specific type.... just an array. Now, given the type you're referring to, I don't think that's exactly what you're asking though...
No, it is not possible. The Array in JS doesn't care what you've put in it, or even that the array indexes are numeric. Java, on the other hand, requires strict typing of both. I'd even go so far as to say that even Object[] is a completely different paradigm from [].
You cannot declare an array to exclusively consist of a particular type. However, you can declare an array (var myArray = [];) and you can add objects of your intended type to it (myArray.push(myMessageType);).
You can declare the array in such a way.
var arr = [];
it can contain object or array of object by calling
arr.push(x)
Reference
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array
Array functions in jQuery

whats the difference between these methods of defining arrays in javascript? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What’s the difference between “Array()” and “[]” while declaring a JavaScript array?
What is the difference between these two methods of defining an array in javascript ?
var arrayList = []
and
var arrayListAgain = new Array();
One is good and the other is bad :-)
No seriously, the first way is shorter (fewer bytes sent over the wire) and it doesn't have any weird potential problems. The second one, however, will work fine.
The weird part with new Array() is this: if you pass one numeric parameter to the constructor, it means "initialize the array so that there are that there are the given number of empty (null) array elements, and so that length is equal to the given number." (Well it has to be an integer, I think actually.) If you pass a single non-number, or two or more numbers, it means, "initialize the array so that its contents reflect this argument list."
Ok now I said there was a weird part, and it's this: if you're using some sort of server side framework, and you want to create an array of numeric values (integer values), like say unique database keys, then you might be tempted to do this:
var keys = new Array(<# favoriteTemplateLanguage.forEach(idList): print(id + ',') #>);
(I made up that syntax of course.) Now what happens if there's just one "id" in your server-side list of keys?
You can use the second one to define an array of a predefined length, e.g.
var arrayListAgain = new Array(20);
will create an array with 20 (undefined) elements.
Also see new Array (len).
none what so ever. Both create a new instance of an Array object.
Douglas Crockford in 'Javascript the good parts' recommends the former method as it is more concise.
They are the same. According to http://www.hunlock.com/blogs/Mastering_Javascript_Arrays:
Current best-practice eschews the
"new" keyword on Javascript
primitives. If you want to create a
new Array simply use brackets [] like
this… var myArray = [];
I recommend reading that page, it contains a lot of useful information about arrays and JS in general.

Javascript: var map = {}; var list = [];

Can someone tell me what exactly the two above lines of javascript do? And more importantly, what it's called so I can search some javascript references to learn about it? I assume they are both creating some form of an array that objects can be added to...?
Curly braces are syntax for creating a Javascript object (which is really a glorified collection of key/value pairs); the brackets make a resizable array.
These are called literals, and they're a handy shortcut to help you make objects and arrays without a lot of typing (good, because you use them all the time). Many other programming languages have similar literal syntax for maps and arrays.
It creates an empty dictionary in map and an empty array in list.
Read up on these structures at http://www.geocities.com/schools_ring/ArrayAndHash.html.

Categories