[{
"circlemarker": [{
"type": "circle_marker"
}, {
"latlong": "abc"
}]
}, {
"connector_marker": [{
"type": "icon_marker"
}, {
"latlong": "pqr"
}]
}, {
"icon_marker": [{
"type": "connector_marker"
}, {
"latlong": "xyz"
}]
}]
I want to access latlong values of each marker. So how can I have access to each property in this structure.
Castrohenge
9,0435 gold badges45 silver badges69 bronze badges
asked Jun 27, 2014 at 14:12
Sagar Bhosale
4051 gold badge5 silver badges19 bronze badges
-
Is your data really structured like that? Does it need to be? That's the first thing I'd change, that looks like it would be a huge headache to work with.Anthony Grist– Anthony Grist2014年06月27日 14:19:31 +00:00Commented Jun 27, 2014 at 14:19
3 Answers 3
You can get latlong data:
for (var a = 0; a < obj.length; a++) {
var key = Object.keys(obj[a])[0];
var latlong = obj[a][key][1];
console.log(latlong));
}
But i think that data have not correct structure, this is better solution:
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"
}];
answered Jun 27, 2014 at 14:25
Rubén Guerrero
2921 silver badge8 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
I think this should work for you:-
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"]);
});
answered Jun 27, 2014 at 14:21
Mritunjay
25.9k7 gold badges57 silver badges71 bronze badges
Comments
so for each object in the array, you want to pluck the latlong from the first key which also references another array of objects. Man I would fix this data structure but if you can't control it, you can do this:
#!/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);
Produces the following output:
[ 'abc', 'pqr', 'xyz' ]
answered Jun 27, 2014 at 14:35
chovy
76.2k63 gold badges249 silver badges325 bronze badges
4 Comments
Rubén Guerrero
Is valid solution, but with nodejs.
chovy
uses lodash or underscore, it works fine anywhere :)
Rubén Guerrero
yes, but require is a nodejs method, unless you use requirejs :)
chovy
you would skip the
var _ = require('lodash') and load <script src=/path/to/lodash.js>lang-js