0

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);
});
31piy
23.9k6 gold badges51 silver badges69 bronze badges
asked Aug 2, 2018 at 13:33
1
  • what is pie_piece in the object? Commented Aug 2, 2018 at 13:38

2 Answers 2

2

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

answered Aug 2, 2018 at 13:37
Sign up to request clarification or add additional context in comments.

Comments

0

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]);
});
answered Aug 2, 2018 at 13:41

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.