I have a multi-dimensional array of objects that I need to transform into a different array. I'm convinced that _.map() is what I need. Not having used it before, I'm having trouble traversing the array to extract the correct values. Given this simplified example:
[
{
"08/25/2015":[
{
"source":"someSource0",
"name":"someName0",
"stuff":"-6.728479",
"stuffValue":"14.862200",
"amount":"-100.00"
},
{
"notNeeded0":-100,
"subtotal":"-100.00"
}
]
},
{
"08/26/2015":[
{
"source":"someSource1",
"name":"someName1",
"stuff":"-9.496676",
"stuffValue":"10.530000",
"amount":"-100.00"
},
{
"notNeeded0":-100,
"subtotal":"-100.00"
}
]
},
{
"08/27/2015":[
{
"source":"someSource2",
"name":"someName2",
"stuff":"-9.469697",
"stuffValue":"10.560000",
"amount":"-100.00"
},
{
"notNeeded0":-100,
"subtotal":"-100.00"
}
]
},
{
"08/28/2015":[
{
"source":"someSource3",
"name":"someName3",
"stuff":"-1.731841",
"stuffValue":"10.570000",
"amount":"-18.24"
},
{
"source":"someSource4",
"name":"someName4",
"stuff":"-2.628939",
"stuffValue":"31.100000",
"amount":"-81.76"
},
{
"notNeeded0":-100,
"subtotal":"-100.00"
}
]
},
{
"notNeeded1":-400,
"notNeeded2":"-400.00"
}
]
I needed to transform it to something structured like this:
[
{
"date":"08/27/2015",
"detail":[
{
"source":"someSource2",
"name":"someName2",
"stuff":"-9.469697",
"stuffValue":"10.560000",
"amount":"-100.00",
"subtotal":"-100.00"
}
]
},
{
"date":"08/28/2015",
"detail":[
{
"source":"someSource3",
"name":"someName3",
"stuff":"-1.731841",
"stuffValue":"10.570000",
"amount":"-18.24",
"subtotal":"-100.00"
},
{
"source":"someSource4",
"name":"someName4",
"stuff":"-2.628939",
"stuffValue":"31.100000",
"amount":"-81.76",
"subtotal":"-100.00"
}
]
}
]
Please feel free to ask questions if needed. Thanks for your assistance.
EDIT: This code is not for web-based use. So any reference to web and browser compatibility is not necessary. And, I use the underscore library to simplify tasks like looping that can get pretty ugly using pure JS. Hope that clarifies the intent.
.mapis pretty straightforward: The callback is invoked for every element in the array and the return value is added to the new array. The documentation even has examples: underscorejs.org/#map .