在javascript中从对象中选择值

时间:2015-01-30 19:16:03

标签: javascript

您好我很难从这本词典中选择价值,

我的对象

[{id: "063f48d0-1452-4dad-8421-145820ddf0f8", 
 storeName: "birr", 
 cost: {
         4fd5ee28-835d-42dc-85a6-699a37bc1948: "54",
         f45827c8-1b1a-48c3-831b-56dab9bcaf3b: "543"
       }, 
 saved: true}]

我需要以某种方式获得54的成本。

请帮助

3 个答案:

答案 0 :(得分:0)

cost中的GUID需要在引号内。

        var obj = [{id: "063f48d0-1452-4dad-8421-145820ddf0f8", 
            storeName: "birr", 
            cost: {
                '4fd5ee28-835d-42dc-85a6-699a37bc1948': "54",
                'f45827c8-1b1a-48c3-831b-56dab9bcaf3b': "543"
        }, 
            saved: true
        }]

        document.write(obj[0].cost['4fd5ee28-835d-42dc-85a6-699a37bc1948']);

输出值54。

答案 1 :(得分:0)



<script>
    var arraylist = [{'id': "063f48d0-1452-4dad-8421-145820ddf0f8", 
        'storeName': "birr", 
        'cost': {
        '4fd5ee28-835d-42dc-85a6-699a37bc1948': "54",
        'f45827c8-1b1a-48c3-831b-56dab9bcaf3b': "543"
        }, 
        'saved': true}];
    
    var costKey = '4fd5ee28-835d-42dc-85a6-699a37bc1948'
    var selectedCost = arraylist[0]['cost'][costKey];
    alert(selectedCost);
</script>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

确保您的密钥在引号中。否则,要检索该值,只需像对象[key]一样访问它,如下面的代码所示。

var stores = [{id: "063f48d0-1452-4dad-8421-145820ddf0f8", 
    storeName: "birr", 
    cost: {
         '4fd5ee28-835d-42dc-85a6-699a37bc1948': "54",
        'f45827c8-1b1a-48c3-831b-56dab9bcaf3b': "543"
    }, 
    saved: true
}];

var store = stores[0];
var cost = store.cost;
var key = Object.keys(cost)[0];
var value = cost[key];
console.log(value);