我想从 http 请求返回的数组中构建一个 JSON 对象,我的实际数组如下所示:
[{
Description: "Product"
IsInstanciable: false
IsMasked: false
Name: "ProductBase"
Subclasses: [{
Description: "Product2"
IsInstanciable: false
IsMasked: false
Name: "ProductBase2",
Count: 5,
Subclasses:[]
},
{
Description: "Product3"
IsInstanciable: false
IsMasked: false
Name: "ProductBase3",
Count: 4,
Subclasses:[],
}]
},
{
Description: "Product4"
IsInstanciable: false
IsMasked: false
Name: "ProductBase4",
Count: '...',
Subclasses: [...]
}
我想从上面的数组递归创建一个 JSON 对象。它看起来像这样:
[
{
name: 'Product',
Count: 9,
children: [
{name: 'Product2'},
{name: 'Product3'},
]
}, {
name: 'Product4',
children: [
{
name: '...',
Count: 'Sum of Count in all children by level'
children: [
{name: '...'},
{name: '...'},
]
}
]
},
];
这是我在打字稿中的递归函数,但它没有按预期工作。我怎样才能解决这个问题?
recursive(data, stack: TreeNode[]) {
let elt: TreeNode = {name:'', children: []}
if(data.Subclasses.length > 0) {
elt.name = data.Description;
data.Subclasses.forEach(element => {
elt.children.push({name: element.Description});
this.recursive(element, stack);
});
}else {
elt.name = data.Description;
}
stack.push(elt);
}
MMMHUHU
墨色风雨
相关分类