我有以下对象:
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]]
等...
答案 0 :(得分:0)
通过使用reduce(),从技术上讲,您不会直接使用任何循环(内部一个循环将迭代输入数据):
function merge(data: { [key: string]: number[] }) {
return Object.getOwnPropertyNames(data).reduce((acc, key) => {
const prefix = key.split('_')[0];
if (acc[prefix] === undefined) {
acc[prefix] = [];
}
acc[prefix].push(data[key]);
return acc;
}, {} as {[key: string]: number[][] })
}
一个例子:
const data = {
a_xx: [1, 2, 3],
b_xx: [9, 8, 7],
a_yy: [11, 22, 33],
b_yy: [9, 8, 7],
c: [9, 8, 7],
};
function merge(data) {
return Object.getOwnPropertyNames(data).reduce((acc, key) => {
const prefix = key.split('_')[0];
if (acc[prefix] === undefined) {
acc[prefix] = [];
}
acc[prefix].push(data[key]);
return acc;
}, {});
}
console.log(merge(data));
答案 1 :(得分:0)
在没有更多要求的情况下,我不能确定这是您想要的,但是这里是一个只有一个循环的示例解决方案。
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 ] ]