Nick
Nick

Reputation: 936

Get value from object key inside JavaScript array

Result of arr[0].price is 'undefined' outside of the function. Why is the variable arr not available when it is defined outside of the function and data is pushed to it?

var arr = [];

function get_data() {

    $.ajax({
      url: 'http://bitcoinprice.co.uk/site-options/',
      dataType: 'json',
      success: function(data) {
        var price = data['gbp_price'];
        var abs_change = data['gbp_abs_change'];
        var p_change = data['gbp_change'];
        var market_cap = data['gbp_market_cap'];
        var today_max = data['gbp_today_max'];
        var today_min = data['gbp_today_min'];

        var obj = {
            'price'      : 50,
            'abs_change' : abs_change,
            'p_change'   : p_change,
            'market_cap' : market_cap,
            'max'        : today_max,
            'min'        : today_min
        };

        arr.push(obj);
        console.log(arr[0].price); // 50
      }

    });

}
get_data();

console.log(arr[0].price) // Uncaught TypeError: Cannot read property 'price' of undefined(…)

I can't seem to find an answer to this. I am trying to get the value from the key 'price' outside of the function get_data().

I'm sure I'm missing something simple here.

Upvotes: 0

Views: 73

Answers (3)

Lalitha
Lalitha

Reputation: 401

var arr is none other than array of objects. You just needed to loop in the array to get value.

var price = 50;
var arr = [];

var obj = {
    'price' : price
}

arr.push(obj);

for(var i of arr)
    {
    console.log(i['price']); //50
    }

Upvotes: 0

Thielicious
Thielicious

Reputation: 4452

Just another option

var price = 50,
        arr = [];
arr.price = price;

console.log(arr.price+'<br>'+arr['price']); // both return 50

Upvotes: 0

Max Koretskyi
Max Koretskyi

Reputation: 105547

You need to use arr[0].price, because the price property is defined not on array, but on the object, that is the first entry in the array.

You code can be rewritten like that to demonstrate what's happening:

var o = {'price':price};
o.price; // 50
arr.push(o);
arr[0] === o; // true

You would have to do like this to actually assign a property to the array:

arr.price = price;

Upvotes: 4

Related Questions