Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a multidimensional array (using Underscore)?

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?

like image 625
GloryOfThe80s Avatar asked Apr 02 '14 01:04

GloryOfThe80s


1 Answers

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' } ] ]
like image 180
thefourtheye Avatar answered Nov 05 '22 05:11

thefourtheye