2014-12-05 83 views
1

我有以下JSON。 我有一个参数给,我需要返回所有的数字。AngularJS JavaScript解析部分JSON

如果我给 “BUS”,我需要return1,38,44,58

JSON的:

{ 
    _id:"23456789", 
    result:[ 
     [ 
     "Car", 
     [ 
      [ 
       2, 
       3, 
       4, 
       6 
      ], 
      [ 
       3, 
       4, 
       444, 
       123 
      ], 
      [ 
       43, 
       34, 
       91446, 
       344473 
      ] 
     ] 
     ], 
     [ 
     "Bus", 
     [ 
      [ 
       1, 
       38, 
       4458, 
       0981 
      ] 
     ] 
     ], 
     [ 
     "Moto", 
     [ 
      [ 
       5, 
       43, 
       41440, 
       804444 
      ] 
     ] 
     ] 
    ] 
} 

这是我的代码:

var coordinates = []; 
    console.log("tag :"+tag); // tag is the parameter "Bus", "Car" or "Moto" 
    $http.get('http://myserver:1234/bbox/'+id) 
        .success(function (response) { 
       var point = {}; 
       // Don't know how to catch a specific word (i.e Car or BUS or Moto) 
       for (var i in response){ 
        var pointName = response.result[i][0]; 
        coordinates.push(response.result[i][1]); 
        points[pointName] = coordinates; 
       } 

    }) 
    .error(function (response) { 
     console.log(response); 
    }); 

已经设置了tag只有一个参数。 只需要返回给定的坐标。

感谢您的帮助!

回答

2

这是JSON响应的非常奇怪的结构,但仍然可以提取必要的数据。例如使用Array.prototype.filter方法:

var coordinates = response.result.filter(function(el) { 
    return el[0] === tag; 
})[0][1][0]; 

为上述代码tag等于“总线”会给你[1, 38, 4458, 981]阵列。

+0

感谢您的回复。我可以做一些类似var coordinates = response.result.filter(function(el)var res = el [0] === tag; console.log(“res”+ res); })[0] [1] [0]; ???? – Jose 2014-12-05 09:56:46

+0

不知道我关注。过滤器必须返回布尔值。 – dfsq 2014-12-05 10:04:54

+0

OOOps我的错误,它的工作原理!关于标签“汽车”,我还会得到所有要点? – Jose 2014-12-05 10:10:39