我对typescript很陌生,我有下面的字典,其中的键和值是浮点数组:
start_to_end_dict
> {-121.95131592,37.253239074: Array(2)}
> -121.95131592,37.253239074: (2) [-131.950349087, 47.253099466]
> [[Prototype]]: Object
我想得到一个密钥列表作为数组列表,如下所示:
> [Array(2)]
> 0: (2) [-121.95131592, 37.253239074]
> length: 1
> [[Prototype]]: Array(0)
但后来我得到了一个字符串列表:
Object.keys(start_to_end_dict)
['-121.95131592,37.253239074']
我注意到values
似乎得到了一个数组列表:
Object.values(start_to_end_dict)
> [Array(2)]
> 0: (2) [-131.950349087, 47.253099466]
> length: 1
> [[Prototype]]: Array(0)
正如其他用户在对您的问题的评论中所指出的:对象的键在JavaScript中总是string
s。您可以编写一个函数来解析字符串坐标,然后迭代对象的条目,使用它来解析每个键的数字坐标值,同时直接访问(已经解析的)值:
下面的正则表达式的解释可以在这里访问。
TS游乐场
type Coords = [number, number];
const coordsRegex = /^s*(?<n1>-?(?:d+.)*d+)s*,s*(?<n2>-?(?:d+.)*d+)s*$/;
function parseCoords (stringCoords: string): Coords {
const groups = stringCoords.match(coordsRegex)?.groups;
if (!groups) throw new Error('Coordinates format not valid');
const coords = [groups.n1, groups.n2].map(Number) as Coords;
return coords;
}
// This is the object value that you showed in the question:
const exampleData: Record<string, Coords> = {
'-121.95131592,37.253239074': [-131.950349087, 47.253099466],
};
for (const [key, value] of Object.entries(exampleData)) {
const keyCoords = parseCoords(key);
console.log({keyCoords, valueCoords: value});
}
从上面的TS操场编译JS:
"use strict";
const coordsRegex = /^s*(?<n1>-?(?:d+.)*d+)s*,s*(?<n2>-?(?:d+.)*d+)s*$/;
function parseCoords(stringCoords) {
const groups = stringCoords.match(coordsRegex)?.groups;
if (!groups)
throw new Error('Coordinates format not valid');
const coords = [groups.n1, groups.n2].map(Number);
return coords;
}
// This is the object value that you showed in the question:
const exampleData = {
'-121.95131592,37.253239074': [-131.950349087, 47.253099466],
};
for (const [key, value] of Object.entries(exampleData)) {
const keyCoords = parseCoords(key);
console.log({ keyCoords, valueCoords: value });
}
试试这个:
const start_to_end_dict = {
'-121.95131592,37.253239074': [-131.950349087, 47.253099466]
};
const arr = [];
Object.keys(start_to_end_dict).forEach(key => {
key.split(',').forEach(elem => arr.push(Number(elem)))
});
console.log(arr);