从矩阵样式的对象数组创建数组数组
Posted
技术标签:
【中文标题】从矩阵样式的对象数组创建数组数组【英文标题】:Create array of arrays from array of objects in the style of a matrix 【发布时间】:2021-08-16 18:51:57 【问题描述】:我有一个对象数组。我正在尝试创建一个类似矩阵的对象数组。
这是我的代码:
let data = [
device: 'iphone', site: 'google', val1:10, val2:20, val3:30,
device: 'iphone', site: 'bing', val1:23, val2:12, val3:14,
device: 'iphone', site: 'jeeves', val1:67, val2:78, val3:12,
device: 'ipad', site: 'google', val1:10, val2:20, val3:30,
device: 'ipad', site: 'bing', val1:23, val2:12, val3:14,
device: 'ipad', site: 'jeeves', val1:67, val2:78, val3:12
];
let arr = data.map(d => Object.values(d));
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
当我像上面那样做地图时,我将所有对象值放入数组数组中。
如何使我的数据看起来像这样:
arr = [
[0,0,67], [0,1,23],[0,2,10],[0,3,67],[0,4,23],[0,5,10],
[1,0,78], [1,1,12],[1,2,20],[1,3,78],[1,4,12],[1,5,20],
[2,0,12], [2,1,14],[2,2,30],[2,3,12],[2,4,14],[2,5,30],
]
不确定如何使我的数组对象看起来像上面的矩阵。
【问题讨论】:
请让你的问题更清楚! @TopW3,我只想将我的对象数组转换为类似于上面的矩阵(arr)。我不知道该怎么做。 【参考方案1】:要仅从每个对象中获取数值,请使用 Array.filter()
,并忽略 NaN
(不是数字)的值:
const data = ["device":"iphone","site":"google","val1":10,"val2":20,"val3":30,"device":"iphone","site":"bing","val1":23,"val2":12,"val3":14,"device":"iphone","site":"jeeves","val1":67,"val2":78,"val3":12,"device":"ipad","site":"google","val1":10,"val2":20,"val3":30,"device":"ipad","site":"bing","val1":23,"val2":12,"val3":14,"device":"ipad","site":"jeeves","val1":67,"val2":78,"val3":12];
const arr = data.map(d => Object.values(d).filter(v => !isNaN(v)));
console.log(arr);
要获取您的矩阵 - 反转数组,映射对象,然后在过滤它们后映射值,并使用索引。将结果展平一层,按照矩阵中每个子数组的第一个值排序。
const data = ["device":"iphone","site":"google","val1":10,"val2":20,"val3":30,"device":"iphone","site":"bing","val1":23,"val2":12,"val3":14,"device":"iphone","site":"jeeves","val1":67,"val2":78,"val3":12,"device":"ipad","site":"google","val1":10,"val2":20,"val3":30,"device":"ipad","site":"bing","val1":23,"val2":12,"val3":14,"device":"ipad","site":"jeeves","val1":67,"val2":78,"val3":12];
const arr = [...data]
.reverse()
.map((d, y) =>
Object.values(d)
.filter(v => !isNaN(v))
.map((v, x) => [x, y, v])
)
.flat(1)
.sort(([a], [b]) => a - b);
console.log(arr);
【讨论】:
感谢您的回复,但结果看起来不像我想要的arr
。它应该看起来像一个矩阵[ [0,0,67], [0,1,23],[0,2,10],[0,3,67],[0,4,23],[0,5,10],...
转换成矩阵的逻辑是什么?
这正是这段代码在做什么......?除非你的意思是第一个对象中的10, 20, 30
应该以某种方式返回0, 0, 67
?
@RoryMcCrossan,是的,所以0,0,67
基本上是(x轴位置,y轴位置,值)
@OriDrori,我正在尝试创建数据的热图。这就是您使用 highcharts 为热图发送的数据以上是关于从矩阵样式的对象数组创建数组数组的主要内容,如果未能解决你的问题,请参考以下文章