AngularJS JavaScript 解析 JSON 的一部分

AngularJS JavaScript Parsing part of JSON

本文关键字:一部分 JSON 解析 JavaScript AngularJS      更新时间:2023-09-26

我有以下JSON。我有一个参数要给出,我需要返回所有数字。

如果我给"BUS",我需要返回1,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已经设置了一个参数。只需要返回给定的坐标。

感谢您的帮助!

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

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

对于等于"总线"的tag上面的代码将为您提供[1, 38, 4458, 981]数组。