arrays - 打字稿对象查找并组合所有以前缀开头的键
问题描述
我有以下对象:
system(1) 中的每个属性都包含三维坐标。有没有一种方法可以合并所有具有相同前缀的属性,而不必在另一个循环中编写循环?这就是我想要实现的目标:
// coordinates of points in systems with prefix lwb
setOfValidPoint1 = [[3.370316528, 0.050628689000000004, 0.20987313800000001],
[3.4050299070000003, 0.559079376, 0.267691772],
[2.990670776, 0.05074561700000001, 0.21216622899999998]]
// coordinates of points in systems with prefix lwb
setOfValidPoint2 = [[3.440000732, 0.04970323, 0.210814064],
[3.4748417970000003, 0.5596490780000001, 0.268024719]]
// coordinates of points in systems with prefix mrf (one point)
setOfValidPoint3 = [[3.51507, 0.777428, 0.36277]]
ETC...
解决方案
如果没有更多要求,我无法确定这是您想要的,但这是一个只有一个循环的示例解决方案。
class TestClass{
lwb_1: number[] = [3.3703, 0.0506, 0.2098];
lwb_2: number[] = [3.4050, 0.5591, 0.2676];
trod_1: number[] = [3.5600, 0.5598, 0.2664];
trod_2: number[] = [3.5201, 0.0494, 0.2111];
}
let test = new TestClass();
let lwbPoints: number[][] = []
let trodPoints: number[][] = []
for(var i in test){
if(test.hasOwnProperty(i)){
let name_split: String[] = i.split('_');
switch(name_split[0]){
case "lwb":
lwbPoints.push(test[i]);
break;
case "trod":
trodPoints.push(test[i]);
break;
default:
console.log("Unexpected class property")
break;
}
}
}
console.log("Points with lwb");
console.log(lwbPoints);
console.log("Points with trod");
console.log(trodPoints);
这给出了以下输出:
Points with lwb
[ [ 3.3703, 0.0506, 0.2098 ], [ 3.405, 0.5591, 0.2676 ] ]
Points with trod
[ [ 3.56, 0.5598, 0.2664 ], [ 3.5201, 0.0494, 0.2111 ] ]