Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract a single value from an array

I am very new to JavaScript so forgive me if this is a dumb question:

I have this Ajax call:

$.ajax({
  type: 'GET',
  url: 'product_prices/' + value,
  success: function (data) {
    console.log('success', data)
  }
});

The value "data" produces an array:

success [{"price":"120.00"}]

What I need, is to extract the value of price (the 120) and use it later in an addition.

How do I get this value out?

like image 417
Vince Avatar asked Jun 22 '26 19:06

Vince


1 Answers

You can do:

var price = data[0]['price'];

or:

var price = data[0].price;

Either of these work like this: you are accessing the first value in your array named data, and then the field in that value named "price". Assigning it to a variable isn't necessary.

However, you would probably want to do this inside a loop, iterating over all values of data so that, in the case the first element of data isn't what you want, you can still catch it. For example:

data.forEach(function(i) {
    console.log(data[i].price);
    //do stuff with the value here
});
like image 182
millerbr Avatar answered Jun 25 '26 09:06

millerbr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!