So I am trying to create a variable that grabs the type_name from an array.
Here is my array.
var customIcons = {
ItemI: {
icon: 'http://...'
type_name: 'East'
},
ItemII: {
icon: 'http://...'
type_name: 'West'
},
ItemIII: {
icon: 'https:...'
type_name: 'North'
},
question: {
icon: 'https:...'
type_name: 'South'
}
}
Here is the variable I am trying to create. I know the php is passing in correctly, but I do not know why it is not grabbing the appropriate type_name from the array:
var buttonText= customIcons[<?php echo $type; ?>].type_name;
I am getting a cannot read property 'type_name' of undefined when I try to use the variable.
Sincere thanks for any help! It is greatly appreciated.
3 Answers 3
You need to rewrite it to
var buttonText= customIcons['<?php echo $type; ?>'].type_name;
See the ' ' around <?php ?>, else it is parsed as a js variable
2 Comments
[] = Array, {} = ObjectI think you forgot the quotes.
var buttonText= customIcons['<?php echo $type; ?>'].type_name;
Comments
I don't know about PHP but here is what is wrong
Your JSON : You have a missing comma
var customIcons = {
item1: {
icon: 'http://...',
type_name: 'East'
},
item2: {
icon: 'http://...',
type_name: 'West'
},
item3: {
icon: 'https:...',
type_name: 'North'
},
question: {
icon: 'https:...',
type_name: 'South'
}
};
console.log(customIcons.item1.icon);
Then Your JSON structure is not ideal
It should have been
var customIcons = [
{
id:"item1",
icon: 'http://...',
type_name: 'East'
},
{
id:"item2",
icon: 'http://...',
type_name: 'West'
},
item: {
id:"item3",
icon: 'https:...',
type_name: 'North'
},
{
id:"item4",
icon: 'https:...',
type_name: 'South'
}
]
Then you can parse this easily using for loop
JSON.parse(text[, reviver])developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…