简体   繁体   中英

Using value of variable in javascript to access JSON Object

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);

});

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

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]);

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM