当“旋转”时避免嵌套地图。多维数组 [英] 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": {
"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
...
}
}
]
为了在谷歌图表中使用我需要更改为格式
that in order to use in a google chart I need to change to the format
[
["2017-05-06", 770, 590, 890, ...],
["2017-05-07", 760, 210, 2200, ...],
["2017-05-08", 1250, 300, 1032, ...]
]
我写了以下内容来进行转换
I wrote the following to make the transformation
let mapped = _.map(
chartData.results[0].timeline_map, (timestampVal, timestampKey) => (
[timestampKey].concat(
_.map(
chartData.results, lineData => (
lineData.timeline_map[timestampKey]
)
)
)
)
)
这有效,但我在考虑嵌套 map
s不是一个好主意,因为它将如何增加被映射数组长度的平方的循环量。有没有更好的方法来达到预期的结果。
This works, but I'm thinking that nesting the map
s is not a good idea because how it will increase the amount of looping by the square off the length of the array being mapped. Is there a better way to achieve the desired result here.
推荐答案
您可以在散列表上使用闭包,日期键。
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) {
return function (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; }
这篇关于当“旋转”时避免嵌套地图。多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文