Reputation: 689
I think I know what the answer is going to be to this question, but maybe someone has a better solution than what I'm thinking of.
If I want to pass 2 arrays to a template, let's say:
arrName = ['one','two','three'];
arrPic = ['one.jpg','two.jpg','three.jpg'];
I want to use the #each helper to loop thru the arrays and put the corresponding name under each picture. Is there a way to do it? Or do I need to create a create a temporary JSON array to make this work, like:
arrCombined = [ { name: 'one', pic: 'one.jpg'}, {name: 'two', pic: 'two.jpg'} etc...
Hopefully this is enough info. Let me know if it's not clear.
Upvotes: 0
Views: 146
Reputation: 5472
Meteor bundles underscore within core so you can use either one of _.zip
or _.object
helpers:
zip_.zip(*arrays)
Merges together the values of each of the arrays with the values at the corresponding position. Useful when you have separate data sources that are coordinated through matching array indexes. If you're working with a matrix of nested arrays, _.zip.apply can transpose the matrix in a similar fashion.
_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
=> [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]
_.zip.apply(_, arrayOfRowsOfData);
=> arrayOfColumnsOfData
object_.object(list, [values])
Converts arrays into objects. Pass either a single list of [key, value] pairs, or a list of keys, and a list of values. If duplicate keys exist, the last value wins.
_.object(['moe', 'larry', 'curly'], [30, 40, 50]);
=> {moe: 30, larry: 40, curly: 50}
_.object([['moe', 30], ['larry', 40], ['curly', 50]]);
=> {moe: 30, larry: 40, curly: 50}
Check the underscore documentation for these and other helpers that you may use in order to be able to construct your combined array in the exact format you want.
Upvotes: 3
Reputation: 19544
Use the temporary JSON.
There's no shortcut. Accessing items of one array while iterating over another would require knowing your current idx in template, which in the last version of Meteor is not yet possible.
Upvotes: 0