I have the following JSON object in my Angular 2 app and would like to know what is the proper what to declare it in typescript.
data = [
{
'id':1,
'title':'something'
'node': [
{
'id':1,
'title':'something'
'node': []
}
]
},
{
'id':2,
'title':'something'
'node': [
{
'id':1,
'title':'something'
'node': []
}
]
}
]
We can create a JSON object in TYPESCRIPT dynamically. There are two types of objects in TypeScript. A Plain Object that we achieve with json. parse() which results in the plain object, and the TypeScript Class, which returns the Class Object.
Use the JSON. parse() method to parse a JSON string in TypeScript, e.g. const result: Person = JSON. parse(jsonStr) . The method parses a JSON string and returns the corresponding value.
Use type assertions to initialize a typed variable to an empty object, e.g. const a1 = {} as Animal; . You can then set the properties on the object using dot or bracket notation. All of the properties you set on the object need to conform to the type. Copied!
Here is an easy and naive implementation of what you're asking for:
interface IDataNode {
id: number;
title: string;
node: Array<IDataNode>;
}
If you want to instantiate said nodes from code:
class DataNode implements IDataNode {
id: number;
title: string;
node: Array<IDataNode>;
constructor(id: number, title: string, node?: Array<IDataNode>) {
this.id = id;
this.title = title;
this.node = node || [];
}
addNode(node: IDataNode): void {
this.node.push(node);
}
}
Using this to hardcode your structure:
let data: Array<IDataNode> = [
new DataNode(1, 'something', [
new DataNode(2, 'something inner'),
new DataNode(3, 'something more')
]),
new DataNode(4, 'sibling 1'),
new DataNode(5, 'sibling 2', [
new DataNode(6, 'child'),
new DataNode(7, 'another child', [
new DataNode(8, 'even deeper nested')
])
])
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With