Angular 向json结果中的所有对象添加字符串值
这是Jason文件的输出:Angular 向json结果中的所有对象添加字符串值,angular,typescript,Angular,Typescript,这是Jason文件的输出: {"children":[{"name":"MyName","value":"MyValue"},{"name":"MyName","value":"MyValue"}]} 现在我希望它是这样的: 如何使用typescript完成此操作 {"children":[{"data":{"name",:"MyName","value":"MyValue"}},{"data":{"name",:"MyName","value":"MyValue"}}]} 这是我的代码:
{"children":[{"name":"MyName","value":"MyValue"},{"name":"MyName","value":"MyValue"}]}
现在我希望它是这样的:
如何使用typescript完成此操作
{"children":[{"data":{"name",:"MyName","value":"MyValue"}},{"data":{"name",:"MyName","value":"MyValue"}}]}
这是我的代码:
export class Parent {
children: Children[];
}
export class Children {
name: string;
value: string;
}
GetHtmlFormElements() {
const children = new Children();
children.name = 'MyName';
children.value = 'MyValue';
const parent = new Parent();
parent.children = [];
parent.children.push(children);
parent.children.push(children);
console.log(JSON.stringify(parent));
}
由于您使用的是角度和素数 您可以为此使用他们自己的类 比如说,
import {TreeNode} from 'primeng/api';
export class dataModel {
name: string;
value: string;
}
export interface data {
data: dataModel;
children?: TreeNode[];//This should be an array
}
这里的子对象将是递归模型。你可以像这样使用它
data: data;
this.data.children = [
{ data: "//put it here//" },
{ data: "//put it here as well//" }
]
当然,您可以使用多种方法来填充此数据对象
注意:你一定要使用Priming的类来完成你的工作
有点容易
//你能试试这个吗 const parent=新父级()
你为什么要这样?这是无效的JSONI如果您查看上面的代码,这里就没有放置数据的地方。你能先修复你的模型吗?换句话说,你不清楚它的结构(模型)是什么。我使用的是Priming组件。它们的结构如下。你能共享与此模型相关的库页面链接吗
parent.children = [];
let temp_obj = {"data":children};
parent.children.push(temp_obj);
parent.children.push(temp_obj);