7

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?

2
  • Do you want the result to be an Array of Arrays like your input? Commented Apr 2, 2014 at 1:33
  • Yes. Exactly the same as the input, but each object would be a Backbone Model. Commented Apr 2, 2014 at 1:35

1 Answer 1

11

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' } ] ]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.