在JSON未完成的错误中访问嵌套对象

时间:2016-06-16 13:25:21

标签: json knockout.js

我在控制台上遇到错误 - screenshot app.js:26 Uncaught TypeError:无法读取属性' location'未定义的

我正在尝试访问该属性 data.places.geomtry.location.lat

 var initialPlaces = {
        "places":
        [{
            "geometry" : {
                "location" :{
                    "lat" : "40.715813",
                    "lng" : "-74.009433"
                }   
            },
            "name" : "Acappella"
        },{
            "geometry" : {
                "location" :{ 
                    "lat" : "40.715813",
                    "lng" : "-74.009433"
                }   
            },
            "name" : "Acappella"
        }
        ]
    }

var Place = function(data){
   console.log(data);
   this.geometry.location.lat = ko.observable(data.geometry.location.lat);
   this.geometry.location.lng = ko.observable(data.geometry.location.lng);
   this.name = ko.observable(data.name);
};

3 个答案:

答案 0 :(得分:0)

这种情况正在发生,因为您试图从列表中获取属性,而不是从对象中获取属性。如果您看到控制台结果返回一个列表,而不是对象位置。你可以这样做:

var initialPlaces = {
   "places": [{
     "geometry": {
       "location": {
         "lat": "40.715813",
         "lng": "-74.009433"
       }
     },
     "name": "Acappella"
   }, {
     "geometry": {
       "location": {
         "lat": "40.715813",
         "lng": "-74.009433"
       }
     },
     "name": "Acappella"
   }]
 }

 var ViewModel = function() {

   var self = this;

   self.place = ko.mapping.fromJS(initialPlaces);
   
 };

 var viewModel = new ViewModel();
 ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
<ul data-bind="foreach: place.places">
  <li>
    <p data-bind="text:$data.name"></p>
    <p data-bind="text:$data.geometry.location.lat"></p>
    <p data-bind="text:$data.geometry.location.lng"></p>
  </li>
</ul>

<强> [编辑]

抱歉,正如您所说,您需要一个嵌套对象,因此我编辑了代码。

答案 1 :(得分:0)

问题出在这里

var Place = function(data) {
   console.log(data);
   this.geometry.location.lat // <<
   ...

您首先需要创建 geometry对象变量,然后添加location属性,最后将您的observable添加到该属性。

var Place = function(data) {

   var self = this;

   self.geometry = {
      location: {
         lat: ko.observable(data.geometry.location.lat),
         lng: ko.observable(data.geometry.location.lng),
      }
   };
};

答案 2 :(得分:0)

基本上,问题是我试图访问一个未创建的对象 - geometry

this.geometry.location.lat

所以,我只能使用

this.lat = ko.observable(data.geometry.location.lat)