I have a large, multidimensional array of JSON objects that I want to map through (using Underscore). For example:
var dummyData = [
[{title: 'a'},{title : 'b'}],
[{title: 'a'},{title : 'b'}],
[{title: 'a'},{title : 'b'}],
[{title: 'a'},{title : 'b'}]
];
For the function body of the _.map
, I want to run each JSON object through a Backbone Model constructor. So far, I've tried something like this to accomplish this:
_.map(dummyData, function() {
_.each(dummyData, function(el, i) {
// run each object through the constructor
}
})
I'm getting caught up on the _.each
, though - since dummyData
isn't actually the 'list' that I want to loop through.
Or am I thinking about this wrong altogether?
Iterate over the elements of dummyData
, with _.map
like this
_.map(dummyData, function(currentDummyData) {
return _.map(currentDummyData, function(el, i) {
// run each object through the constructor
})
});
dummyData
is an Array of Arrays. When you use _.map
with that, it picks up each array in the array of arrays and passes to the function, which we accept with function(currentDummyData) {..}
.
Inside that function, we again _.map
that array, because it is still an array. So, we iterate that to get individual elements and pass them to the function function(el, i) {..}
, where new Backbone models are created.
Note: You have to return the result of _.map
, like in the answer. Because, _.map
expects the function called to return an object and all the returned objects will be gathered to create a new array.
For example,
console.log(_.map(dummyData, function(currentDummyData) {
return _.map(currentDummyData, function(el, i) {
return {title: el.title + el.title};
})
}));
will produce
[ [ { title: 'aa' }, { title: 'bb' } ],
[ { title: 'aa' }, { title: 'bb' } ],
[ { title: 'aa' }, { title: 'bb' } ],
[ { title: 'aa' }, { title: 'bb' } ] ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With