无法访问所有json属性
问题描述:
我有这个json结构,出于某种原因,我无法访问其他属性。我只能通过type
,properties
等主要属性“访问”该层级。但我无法访问icon
,iconURL
,title
。数据在那里,但我可以单独访问。无法访问所有json属性
如果我使用console.log(markerRE[i].properties)
,它会显示所有属性,但如果我只想要标题,则控制台会触发can't read property properties of undefined
。
var markerRE = [{}]; //JSON ARRAY
$.ajax({
url: 'consulta4.php',
data: {},
method: 'POST',
dataType: 'json',
success: function (data) {
for (var i = 0; i < Object.keys(data).length; i++) {
markerRE.push({
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [data[i].longitude, data[i].latitude]
},
"properties": {
"title": "Emergencia: " + data[i].priority,
"id": data[i].id_emergency,
//"descripcion":"<button class='RE'>oisdjos</button>", Forma alternativa de añadir html
"icon": {
"iconUrl": data[i].imagen,
"iconSize": [50, 50], // size of the icon
"iconAnchor": [25, 50], // point of the icon which will correspond to marker's location
"popupAnchor": [0, -25], // point from which the popup should open relative to the iconAnchor
"className": "dot"
}
}
}
);
console.log(markerRE[i].properties.title);
}
}
});
答
它没有很大的意义对我来说你在上面做什么,只要通过按键在您的数据的数量的循环。但我认为你的问题之一是你正在实例化markerRE,其中已经有一个空对象。而不是仅仅把它变成一个空的数组[]。所以console.log(markerRE [0] .properties.title);将是无效的,因为markerRE [0]是一个空对象
答
你尝试宣告markerRE作为
var markerRE = []; //without {}
我想在我自己的方式BT不知道和我不知道为什么,但使用{}使计数器从1开始不是0.
你为什么要迭代Object.keys? – Rayon
即时迭代它,因为我想存储来自ajax的所有数据 –
['Object.keys'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys )将返回对象的属性。您可能需要一个for循环。需要查看'数据' – Rayon