Avoiding Nesting Maps When "pivoting" Multidimensional Array
I have data in the format [ { 'timeline_map': { '2017-05-06': 770, '2017-05-07': 760, '2017-05-08': 1250 ... } }, { 'timeline_map': {
Solution 1:
You could use a closure over a hash table and assign the values accordingly to the date keys.
var data = [{ timeline_map: { "2017-05-06": 770, "2017-05-07": 760, "2017-05-08": 1250 } }, { timeline_map: { "2017-05-06": 590, "2017-05-07": 210, "2017-05-08": 300 } }, { timeline_map: { "2017-05-06": 890, "2017-05-07": 2200, "2017-05-08": 1032 } }],
grouped = data.reduce(function (hash) {
returnfunction (r, o) {
Object.keys(o.timeline_map).forEach(function (k) {
if (!hash[k]) {
hash[k] = [k];
r.push(hash[k]);
}
hash[k].push(o.timeline_map[k]);
});
return r;
};
}(Object.create(null)), []);
console.log(grouped);
.as-console-wrapper { max-height: 100%!important; top: 0; }
Solution 2:
Merge the objects using _.mergeWith()
, and then _.map()
the resulting object to an array of arrays:
const arr = [{
"timeline_map": {
"2017-05-06": 770,
"2017-05-07": 760,
"2017-05-08": 1250
}
},
{
"timeline_map": {
"2017-05-06": 590,
"2017-05-07": 210,
"2017-05-08": 300
}
},
{
"timeline_map": {
"2017-05-06": 890,
"2017-05-07": 2200,
"2017-05-08": 1032
}
}
];
const result = _.map(_.mergeWith({}, ...arr, (o1, o2) => {
if(Array.isArray(o1)) {
o1.push(o2)
return o1;
}
if(_.isNumber(o2)) {
return [o2];
}
}).timeline_map, (v, k) => [k, ...v]);
console.log(result);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Post a Comment for "Avoiding Nesting Maps When "pivoting" Multidimensional Array"