简体   繁体   English

在javascript中使用变量值访问JSON对象

[英]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. 我正在尝试使用HTML中某些文本的值访问我的Pie对象。

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. 当使用点符号对对象pie.pie_piece进行属性访问时, pie_piecepie对象中查找实际名称为pie_piece的属性。

To use the value of pie_piece you will want to use bracket notation 要使用pie_piece的值,您将需要使用方括号表示法

pie[pie_piece]

more on property access 有关财产访问的更多信息

You can access elements of an object by using the notation object['element'] . 您可以使用object['element']表示法访问object['element'] So in this case you could do something like pie[pie_piece] if pie_piece is welfare , health , or state_pensions . 因此,在这种情况下,如果pie_piece是welfarehealthstate_pensions ,则可以执行类似pie[pie_piece] 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]);

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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