最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to extract a single value from an array - Stack Overflow

programmeradmin7浏览0评论

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?

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?

Share Improve this question edited Feb 4, 2016 at 0:43 Crescent Fresh 117k27 gold badges157 silver badges140 bronze badges asked Feb 4, 2016 at 0:30 VinceVince 1,5352 gold badges23 silver badges36 bronze badges 1
  • console.log(data.price)? – Yehia Awad Commented Feb 4, 2016 at 0:33
Add a ment  | 

5 Answers 5

Reset to default 3

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

data has an array of objects with a price property. Access the first object in the array and parse it's price as a number:

parseFloat(data[0].price);

Test it, You must parse JSON string before using it!

var data = JSON.parse('[{"price":"120.00"}]'); var Price = data[0].price; // 120.00 //OR IF it's Single And not Array var Price = data.price; // 120.00

Since your response is an array, access the first position, and then access the object property:

data[0].price; //"120.00"
var result = {},
    sum    = 0;
$.ajax({
    type: 'GET',
    url: 'product_prices/' + value,
    success: function (data) {
        result = data[0];
    }
});

sum = parseFloat(result.price) + 2.25;
发布评论

评论列表(0)

  1. 暂无评论