I’m using underscore.js, of course any solution is fine, but I have an object that looks like this:
{ '4f871d4967e04':
[ { _id: 4f871d4adaf6fa492f000001,
product_id: 4f871d43daf6fa4e2f000002,
width: '300',
height: 300,
group: '4f871d4967e04' },
{ _id: 4f871d4adaf6fa492f000004,
product_id: 4f871d43daf6fa4e2f000002,
width: '150',
height: 150,
group: '4f871d4967e04' },
{ _id: 4f871d4bdaf6fa492f000007,
product_id: 4f871d43daf6fa4e2f000002,
width: '100',
height: 100,
group: '4f871d4967e04' },
{ _id: 4f871d4bdaf6fa492f00000a,
product_id: 4f871d43daf6fa4e2f000002,
width: '75',
height: 75,
group: '4f871d4967e04' } ],
'4f871d51200de':
[ { _id: 4f871d51daf6faf42e000001,
product_id: 4f871d43daf6fa4e2f000002,
width: '300',
height: 300,
group: '4f871d51200de' },
{ _id: 4f871d52daf6faf42e000004,
product_id: 4f871d43daf6fa4e2f000002,
width: '150',
height: 150,
group: '4f871d51200de' },
{ _id: 4f871d53daf6faf42e000007,
product_id: 4f871d43daf6fa4e2f000002,
width: '100',
height: 100,
group: '4f871d51200de' },
{ _id: 4f871d53daf6faf42e00000a,
product_id: 4f871d43daf6fa4e2f000002,
width: '75',
height: 75,
group: '4f871d51200de' } ] }
I’d like to turn it to this:
{"4f871d4967e04" : {
"300" : {
_id : '',
}
"150" : {
_id : '',
}
"100" : {
_id : '',
}
"75" : {
_id : '',
}
}, "4f871d4967e04" : {
"300" : {
_id : '',
}
"150" : {
_id : '',
}
"100" : {
_id : '',
}
"75" : {
_id : '',
}
}
This way I can iterate through each “group” and simply use this["300"] to get the size that I want. I’m iterating through this in Handlebar’s templates, so I’m limited to what conditions I can check for.
Any suggestions would be really helpful.
Thank you!
The obvious plain-jane JavaScript approach would probably be the quickest:
Simply loop through the main object (
data) key by key and use an inner loop to rearrange the arrays into width→object mapping tables.Anything you come up with will probably be that nested loop in disguise. The Underscore version would look something like this:
That’s pretty much the original nested
forloop set up withreducein place of the loops. You’re pretty much limited to usingreducehere as most Underscore functions really want to turn everything into an array. You could useeach:But that’s the same as the
reduceapproach with temporary variables. You could probably come up with other approaches but they’ll probably just be more variations on this theme.Demo: http://jsfiddle.net/ambiguous/ffcUC/2/
If you want to send your data into a Handlebars template like:
Then you only want the values from what the above produces. But in this case, you can adjust your loops to save some work:
Or switch to
reduceinside amap:Demo: http://jsfiddle.net/ambiguous/tsx7z/