在Angular中展开/还原嵌套的JSON对象可以使用递归来实现。下面是一个使用Angular的示例代码:
1.在组件中定义一个方法来展开/还原嵌套的JSON对象:
export class AppComponent {
data: any = {
name: 'John',
age: 30,
address: {
street: '123 Main St',
city: 'New York',
state: 'NY'
}
};
expandedData: any;
toggleExpansion() {
this.expandedData = this.expandObject(this.data);
}
expandObject(obj: any) {
const expandedObj = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
if (typeof obj[key] === 'object') {
const expandedChildObj = this.expandObject(obj[key]);
for (const childKey in expandedChildObj) {
if (expandedChildObj.hasOwnProperty(childKey)) {
expandedObj[key + '.' + childKey] = expandedChildObj[childKey];
}
}
} else {
expandedObj[key] = obj[key];
}
}
}
return expandedObj;
}
}
2.在组件的HTML模板中使用展开后的数据:
{{ expandedData | json }}
这个示例中,expandObject
方法使用递归来展开嵌套的JSON对象。对于每个对象中的属性,如果属性的类型是对象,则递归调用expandObject
方法,并将展开后的子对象的属性添加到父对象中的新属性中。如果属性的类型不是对象,则直接将属性添加到展开后的对象中。
在HTML模板中,通过点击按钮来触发toggleExpansion
方法,展开/还原嵌套的JSON对象。展开后的数据使用json
管道进行格式化,并在页面上显示出来。