Reputation: 37085
Sorry, I know this is programming 101, but I can't find any good documentation...
I have an array, and I want to cast each member as an object and then call them by the name assigned (this would be so much simpler if javascript allowed for non-number index values). For instance:
var things = ['chair', 'tv', 'bed'];
var costs = ['10', '100', '75'];
for (var i = 0; i < things.length; i++) {
thing.name = things[i];
thing.cost = costs[i];
}
alert(thing.name('tv').cost);
Obviously this isn't the way to do this, but the desired outcome would be an alert that said "100".
I have gotten as far as creating a class that has a method called name which points back to the main object, like so:
function thing(name, cost) {
function name(thename) {
return this;
}
this.thingname = name;
this.name = name;
this.cost = cost;
}
But this still requires that each object has a unique variable name, which goes against the whole point. What I want is to simply throw all of my array into some generic class and call the values I need by the name.
I know this is probably way to easy to ask here, but I'm stuck!
Thanks.
Upvotes: 0
Views: 212
Reputation: 32129
If you need to do this using your original data format (because you have no influence on it) use the following:
var things = ['chair', 'tv', 'bed'];
var costs = ['10', '100', '75'];
var associatedThings;
for(i=0,x=things.length;i<x;i++){
associatedThings[things[i]] = {cost: costs[i]};
}
alert(associatedThings['tv'].cost);
Upvotes: 0
Reputation: 40512
why don't you try JSON:
like
var myArray= {"things": [
{"name":"chair","price":"10"},
{"name":"tv","price":"100"},
{"name":"bed","price":"75"}
]};
//now you can use it like this
for(var i=0; i< myArray.things.length; i++)
{
alert(myArray.things[i].name + " costs " + myArray.things[i].price);
}
Upvotes: 0
Reputation: 5169
use Why don't define your arrays as an object like
var things = {'chair':10, 'tv':100, 'bed':75}
Then you can access prices like properties of an associative array
things.chair
would give you 10
Upvotes: 1
Reputation: 13421
How about just using a dictionary object:
var things = {'chair':10, 'tv':100, 'bed':75};
alert(things['chair'])
// if you want to use things['chair'].cost, it'd look more like this:
var things = {'chair': {cost: 10}, 'tv': {cost: 100}, 'bed': {cost: 75}};
Upvotes: 1
Reputation: 5304
var stuff = {
chair: 10,
tv: 100,
bed: 75
};
alert(stuff.chair); // alerts '10'
alert(stuff['chair']); // alerts '10'
stuff.house = 100000;
stuff['car'] = 10000;
alert(stuff['house']); // you get the picture...
alert(stuff.car);
Upvotes: 2
Reputation: 488734
Why not use objects?
var things = {
chair: 10,
tv: 100,
bed: 75
};
alert(things.chair); // 10
alert(things['tv']); // 100
Upvotes: 5