[英]How to traverse an Object in Typescript?
我有一個接收對象的函數,它看起來像下面的一個,
Object(12)
0: "UQ"
1: "YTL"
2: "VZW"
3: "LGT"
4: "KDDI"
5: "KT"
6: "SPRINT_T"
7: "RIL"
8: "SKT"
9: "SPRINT"
10: "KPS"
11: "GLB1"
並將其分配給變量名稱是 results: string [];
現在我使用 forEach 遍歷整個數組,但我不能。 然后我打印顯示 0 的對象的長度。
但我可以使用 results[0] 或 results[1] 訪問名稱。 但我不能使用循環。
現在,我如何遍歷整個對象並訪問所有名稱,如“UK”、“YTL”。
使用 Object.keys()。 由於這不是數組而是對象,因此不能使用 forEach。
Object.keys(myObject)
.sort((x, y) => x >= y ? 1 : -1) // for order preserving, can be omitted if order doesn't matter
.forEach(key => {
const value = myObject[key];
})
在 Typescript 中,您可以通過兩種方式分配 json 數據。
假設您將 json 數據存儲在變量名 data.json 中。 然后您可以按原樣分配它。
data: string[];
this.service.getData()
.subscribe(
(data: string[]) => {
this.data = data;
});
通過這種方式,您可以使用 Foreach 或您對這個問題的期望。
通過這種方式,您可以將該 json 數據分配為您在問題中顯示的對象。
data: string[];
this.service.getData()
.subscribe(
(data: string[]) => {
this.data = {... data };
});
在您的問題中,您必須使用第一個。
我通過TypeScript
創建了一個示例來遍歷一個對象並獲取所有終端節點,希望對您有所幫助:
function getCurrentLevelTerminalNodes(obj: any, maxDepth = 100) {
if (maxDepth <= 0) {
throw new Error('Too deep to traverse!');
}
const res: any[] = [];
Object.keys(obj).forEach(value => {
if (typeof obj[value] !== 'object') {
res.push(obj[value]);
} else {
res.push(...getCurrentLevelTerminalNodes(obj[value], maxDepth - 1));
}
});
return res;
}
export default function getTerminalNodes(obj: Object) {
return getCurrentLevelTerminalNodes(obj);
}
import getTerminalNodes from './terminal-node';
describe('terminal-node', () => {
it('get all terminal nodes', () => {
const testObj = {
a: {
b: {
c: 'c',
},
},
b: 'b',
};
expect(getTerminalNodes(testObj)).toStrictEqual(['c', 'b']);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.