我有下面的JavaScript递归逻辑其中i要实现在角度相同的
var dictionary = {
'Key1': '1',
'Key2': {
'a' : '2',
'b' : '3',
'c' : {
'd' : '3',
'e' : '1'
}
}
}
function flattenDictionary(dictionary) {
var flattenedDictionary = {};
function flattenDitionaryHelper(dictionary, propName) {
if (typeof dictionary != 'object') {
flattenedDictionary[propName] = dictionary;
return;
}
for (var prop in dictionary) {
if (propName == ''){
flattenDitionaryHelper(dictionary[prop], propName+prop);
} else {
flattenDitionaryHelper(dictionary[prop], propName+'.'+prop);
}
}
}
flattenDitionaryHelper(dictionary, '');
return flattenedDictionary;
}
flattenDictionary(dictionary);
我所做的是
public flatStruct(struc) {
this.flatDictionary = {};
let propName;
let description;
if(typeof struc != 'object'){
this.flatDictionary[propName] = struc;
console.log(this.flatDictionary);
}
for(var prop in struc){
if(propName=''){
description = struc[prop];
console.log(description);
}
}
}
ngOnInit() {
this.flatStruct(this.dict);
}
但我坚持一些在那里,我无法得到控制台日志也是第一次尝试,我能够后来获得初始登录我我无法获取数据
干得好。在打字稿你可以通过替代this
调用方法分离的嵌套函数。
export class AppComponent implements OnInit, OnDestroy {
private flattenedDictionary = {};
ngOnInit(): void {
this.go();
}
ngOnDestroy(): void {}
private go(): void {
const dictionary = {
'Key1': '1', 'Key2': {
'a': '2', 'b': '3', 'c': {
'd': '3', 'e': '1'
}
}
};
this.flattenDictionary(dictionary);
console.log(this.flattenedDictionary);
}
flattenDictionary(dictionary): any {
this.flattenDictionaryHelper(dictionary, '');
}
flattenDictionaryHelper(dictionary, propName): void {
if (typeof dictionary !== 'object') {
this.flattenedDictionary[propName] = dictionary;
return;
}
for (const prop in dictionary) {
if (propName === '') {
this.flattenDictionaryHelper(dictionary[prop], propName + prop);
} else {
this.flattenDictionaryHelper(dictionary[prop], propName + '.' + prop);
}
}
}
}