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

javascript - Get single value from JSON object - Stack Overflow

programmeradmin0浏览0评论

I am using Google Maps API with jQuery getJSON:

$.getJSON(requestUrl, function(data) {
        var distance = //need to parse value from 'data' object here
    });

data object's structure is like this: (example)

I need to set my variable distance to 225 mi in this case

I am using Google Maps API with jQuery getJSON:

$.getJSON(requestUrl, function(data) {
        var distance = //need to parse value from 'data' object here
    });

data object's structure is like this: (example)

I need to set my variable distance to 225 mi in this case

Share Improve this question asked Jun 1, 2016 at 13:45 Gintas KGintas K 1,4783 gold badges18 silver badges39 bronze badges 1
  • 1 Can you please replace the image with code? It is much easier for people to try and reconstruct your issue copying and pasting code, rather than reading it from an image. – Tushar Commented Jun 1, 2016 at 13:47
Add a ment  | 

3 Answers 3

Reset to default 2
$.getJSON(requestUrl, function(data) {
    var distance = data.rows[0].elements[0].distance.text;
});

Pretty simple, but I do want to know if you'll ever get more then one row or element from your function?

data.rows.forEach(function(value){ 
    value.elements.forEach(function(childValue) {
      console.log(childValue.distance.text);
    });
});

The above nested forEach should get you the distance value.

var json = JSON.parse(data);
distance= json["rows"]["elements"]["distance"]["text"];

Hope it helps

发布评论

评论列表(0)

  1. 暂无评论