[{
"circlemarker": [{
"type": "circle_marker"
}, {
"latlong": "abc"
}]
}, {
"connector_marker": [{
"type": "icon_marker"
}, {
"latlong": "pqr"
}]
}, {
"icon_marker": [{
"type": "connector_marker"
}, {
"latlong": "xyz"
}]
}]
我想访问每个标记的latlong
值。那么如何才能访问此结构中的每个属性。
答案 0 :(得分:2)
您可以获取latlong数据:
for (var a = 0; a < obj.length; a++) {
var key = Object.keys(obj[a])[0];
var latlong = obj[a][key][1];
console.log(latlong));
}
但我认为数据结构不正确,这是更好的解决方案:
var markers = [{
"name": "circlemarker",
"type": "circle_marker"
"latlong": "abc"
}, {
"name": "connector_marker",
"type": "icon_marker",
"latlong": "pqr"
}, {
"name": "icon_marker",
"type": "connector_marker",
"latlong": "xyz"
}];
答案 1 :(得分:1)
我认为这应该适合你: -
var makers = [{"circlemarker":[{"type":"circle_marker"},{"latlong":"abc"}]},{"connector_marker":[{"type":"icon_marker"},{"latlong":"pqr"}]},{"icon_marker":[{"type":"connector_marker"},{"latlong":"xyz"}]}];
makers.forEach(function(maker){
var makerName = Object.keys(maker)[0];
console.log(maker[makerName][1]["latlong"]);
});
答案 2 :(得分:-1)
因此,对于数组中的每个对象,您希望从第一个键中提取latlong
,该键也引用另一个对象数组。我会修复这个数据结构,但如果你无法控制它,你可以这样做:
#!/usr/bin/env node
var data = [{
"circlemarker": [{
"type": "circle_marker"
}, {
"latlong": "abc"
}]
}, {
"connector_marker": [{
"type": "icon_marker"
}, {
"latlong": "pqr"
}]
}, {
"icon_marker": [{
"type": "connector_marker"
}, {
"latlong": "xyz"
}]
}];
var _ = require('lodash')
, coords = [];
_.each(data, function(item){
//console.log(item);
var key = _(Object.keys(item)).first()
, first = item[key]
, latLong = _.pluck(first, 'latlong')[1];
if ( latLong ) {
coords.push(latLong);
}
});
console.log(coords);
产生以下输出:
[ 'abc', 'pqr', 'xyz' ]