如何在JS中将大的一维数组转换为小键对对象系列?

时间:2018-06-20 02:46:36

标签: javascript three.js

我正在尝试用threeJS创建手绘草图。大部分零件已经完成并且能够绘制形状。现在,我的下一步是使用simplify-JS简化多边形中的点。 令人担心的是,我将数组作为缓冲区几何传递,并使用“线网格”在屏幕上绘制。我正在创建数组[x,y,z,x,y,z,x,y,z ...依此类推]直到MAX_POINTS在我的情况下是10000。例子

Vertices[0.555,0.323,298,0.585,0.353,298,0.615,0.373,298...continuous].

现在如何将这些顶点转换为

Vertices[{x:0.555,y:0.323,z:298}, {x:0.585,y:0.353,z:298},{x:0.615,y:0.373,z:298}]

..依此类推,直到Vertices.length。

谢谢。

4 个答案:

答案 0 :(得分:3)

您可以使用简单的for循环遍历数组并将对象推入新数组中。

var vertices = [0.555,0.323,298,0.585,0.353,298,0.615,0.373,298];
var convertedVertices = [];

for(let i = 0; i < vertices.length; i += 3){
  convertedVertices.push({ x: vertices[i], y: vertices[i+1], z: vertices[i+2] })
}

console.log(convertedVertices);

已更新:

要将数组转换回1D顶点。

let revert = convertedVertices.reduce(((acc, obj) => acc.concat(obj.x, obj.y, obj.z)), []);

JSBin:https://jsbin.com/sohakufope/edit?js,console

JSBin:https://jsbin.com/bodazugeco/1/edit?js,console

答案 1 :(得分:1)

var nverts = [];
for(var i=0;i<vertices.length;i+=3)nverts.push(new THREE.Vector3(vertices[i],vertices[i+1],vertices[i+2]);

答案 2 :(得分:1)

希望有帮助

var vertices = [
    0.555,0.323,298,
    0.585,0.353,297,
    0.615,0.373,296,
    0.123,0.456,295,
    0.789,0.012,294,
    0.234,0.569,293];

if (vertices.length % 3 === 0) {
    var result = [];
    for(var i=0; i < vertices.length; i+=3) {
        result.push({ x: vertices[i], y: vertices[i+1], z: vertices[i+2] });
    }
    console.table(result);
}

答案 3 :(得分:0)

如果您有与此相关的测试数据,那就太好了,但我认为类似以下的内容应该可以正常工作。

const keysMap = ['x', 'y', 'z']
let transformedArr = [];
let vertices = [0.555,0.323,298,0.585,0.353,298,0.615,0.373,298...continuous]
while (vertices.length) {
  vector = {};
  vertices.slice(o, 2).forEach( (val, ind) => {vector[keyMap[ind]] = val} );
  transformedArr.push(vector);
  vertices = vertices.slice(3);
}