How to log a certain field of every model in a col

2019-07-25 13:16发布

问题:

Hi im trying to output every "lat" field from my collection. However anything i do returns the right number of results but they all say undefined, the data is definitely there and the names are definitely right. I've tried using pluck and _.each with a get inside the function and all it ever says is undefined.

This is the current method im trying

var ccLocal = window.router.carsCollection;
_.each(ccLocal.models, function(model) {
    console.log(model.lat);
})

logging ccLocal returns the entire collection with all its data so its definitely there. What am i doing wrong?

Using model.get("lat") also fails.

Using console.log(ccLocal.at(0).attributes); returns this

Object {unitID: "03_Cow_30", positionHistory: Array[1]}
positionHistory: Array[1]
0: Object
estimatedSpeed: "39"
isToday: false
lastSoundFileName: "F11"
lastSoundRange: "11"
lastSoundTime: "2008-10-29 20:38:25"
lat: "51.466227"
long: "-0.491647"
minutesAgo: 1016726
status: "1"
time: "2011-07-13 16:03:37"
__proto__: Object
length: 1
__proto__: Array[0]
unitID: "03_Cow_30"
__proto__: Object

回答1:

Ah, so your model attributes data structure is not what everyone thought. Based on your attributes structure, you need something like this. It's a bit fragile due to assuming positionHistory is an array with at least one element, but that's where your data is.

var ccLocal = window.router.carsCollection;
_.each(ccLocal.models, function(model) {
   console.log(model.get('positionHistory')[0].lat);
})