Reputation: 553
I've got a question,
I've got an array in Javascript that looks like this:
var plans = [{
'advanced':[{
'price':'10',
'name':'Advanced'
}],
'basic':[{
'price':'20',
'name':'Basic'
}]
}];
And there's a variable called plan, this could be advanced or basic etc. Now I want to display the price from the array that corresponds with the variable plan. How do I get the price?
I've tried things like:
PS: I am originally A PHP developer, maybe my PHP influence is blocking the correct thoughts, i dont know...
Upvotes: 0
Views: 85
Reputation: 3997
you have some extra array cruft, where you have arrays with one item in them instead of just having the object.
var plans = {
advanced: {
price: '10',
name: 'Advanced'
},
basic: {
price: '20',
name:' Basic'
}
};
if you have var plan ="advanced"
you can just do plans[plan].price
if you NEED the current structure with the arrays then it is essentially the same thing but
var plan ="advanced"
plans[0][plan][0].price
hope that helps
Upvotes: 2
Reputation: 16020
Access it like this: plans[0].advanced[0].price
That's the wrong way to be going about it though; just use JavaScript objects:
var plans = {
advanced: {
price: '10',
name: 'Advanced'
},
basic: {
price: '20',
name:' Basic'
}
};
Then you can access it using plans.advanced.price
, which is much more clear.
Note that plans.advanced.price
is the same as plans['advanced']['price']
in JavaScript, there is no difference.
Arrays in JavaScript are just glorified objects - as such there is no such thing as "associative arrays" in JavaScript, objects perform the same thing as associative arrays in PHP.
Upvotes: 5