Reputation: 13
I'm trying to access my pie object using the value of some text in HTML.
However, the code is using the name of the variable as opposed to the value of the variable.
This seems like it should be obviously to me, but it's got me stumped.
Thanks
var pie = {
welfare: {
title: "Welfare",
percentage : 24,
point: 0,
color: '#601C6B'
},
health: {
title: "Health",
percentage : 20,
point: 0,
color: '#FFAA97'
},
state_pensions: {
title: "State pensions",
percentage : 13,
point: 0,
color: "#9C9C9C"
}
}
$('.pie_item').click(function(){
var pie_piece = $(this).text();
console.log("this is " + pie_piece);
$(this).closest(".drop_down_button").find('p').text(pie_piece);
console.log(pie.pie_piece);
});
Upvotes: 0
Views: 55
Reputation: 46
You can access elements of an object by using the notation object['element']
. So in this case you could do something like pie[pie_piece]
if pie_piece is welfare
, health
, or state_pensions
.
var pie = {
welfare: {
title: "Welfare",
percentage : 24,
point: 0,
color: '#601C6B'
},
health: {
title: "Health",
percentage : 20,
point: 0,
color: '#FFAA97'
},
state_pensions: {
title: "State pensions",
percentage : 13,
point: 0,
color: "#9C9C9C"
}
}
$('.pie_item').click(function(){
var pie_piece = $(this).text();
console.log("this is " + pie_piece);
$(this).closest(".drop_down_button").find('p').text(pie_piece);
console.log(pie[pie_piece]);
});
Upvotes: 0
Reputation:
When you use dot notation for property access on an object pie.pie_piece
it is looking for a property with the actual name pie_piece
in the pie
object.
To use the value of pie_piece
you will want to use bracket notation
pie[pie_piece]
more on property access
Upvotes: 2