如何解决如何从 Typescript
我在查找 npm 包或创建自己的函数以从此类中的元素生成 json 文件时遇到问题:
export class TranslatedFileElement {
private key: string
private hasChild: boolean // True if vaule is empty,vaules not empty; False if value not empty,values is empty
private value?: string // One of them should be required,because if TranslatedFileElement have any childs,private values?: TranslatedFileElement[] // then value should be empty,if not,values should be empty
private isTranslated?: boolean
public constructor() {
this.key = '',this.hasChild = false,this.value = '',this.values = null,this.isTranslated = false
}
public setTranslateFileElement(
_key: string,_value: string,_values: TranslatedFileElement[],_hasChild: boolean,_isTranslated: boolean
) {
this.key = _key
this.value = _value
this.values = _values
this.hasChild = _hasChild,this.isTranslated = _isTranslated
}
public setKey(_key: string) {
this.key = _key
}
[...] //Other get's and set's
}
我尝试过类似的方法,但它无法正常工作并且产生的问题比解决的还多:
private converter(elementsToJSON: TranslatedFileElement[],nestedLevel: number = 0): string {
let JSONResult = '{'
elementsToJSON.forEach((element) => {
JSONResult = JSONResult + '"' + element.getKey() + '" : '
if (element.getHasChild()) {
JSONResult = JSONResult +
this.converter(element.getValues(),nestedLevel + 2)
} else {
JSONResult = JSONResult + '"' + element.getValue() + '",'
}
})
JSONResult = JSONResult + '},'
JSONResult = JSON.parse(JSON.stringify(JSONResult));
return JSONResult
}
有人知道好的 npm(未弃用)包可以做到这一点,或者有想法简单地解决它?
解决方法
我建议添加一个方法,将该结构转换为与您想要的 json 具有相同结构的对象,并在如此创建的对象上调用 JSON.stringify 。
class TranslatedFileElement {
...
public toJSON(){
return JSON.stringify(this.toObject());
}
public toObject(){
let val:any=null;
if (this.hasChild){
const reducer = (acc:any,val:any) => ({...acc,...val});
if (this.values)
val = this.values.map((child:TranslatedFileElement)=>child.toObject()).reduce(reducer,{});
}else{
val = this.value;
}
return {[this.key]:val};
}
...
}
,
你可以做的只是调用
JSON.stringify(elementsToJSON);
类属性将被转换为 JSON。
唯一的问题是如果您的数据结构不是树并且其中包含循环。