gpt4 book ai didi

javascript - 如何使用函数更改使用 JSON 的响应?

转载 作者:行者123 更新时间:2023-12-04 03:45:52 25 4
gpt4 key购买 nike

我正在调用函数 buildFileTree 并将其响应保存到常量数据中

const data = this.buildFileTree(dataObject, 0);

dataObject 是:

 const dataObject =  JSON.parse(TREE_DATA);

TREE_DATA 是:

const TREE_DATA = JSON.stringify([
{
Standard: "Food",
Category: [
{
Name: "Vegetable",
Tables: [
{
Description:
"The carrot is a simple root vegetable, usually conical or cylindrical in shape.",
Name: "Carrots"
},
{
Description:
" tomatoes come in a wide variety of shapes: round, oblate, pear-shaped, torpedo-shaped,",
Name: "Tomatoes"
}
]
},
{
Name: "Fruits",
Tables: [
{
Description: "Oranges",
Name: "Spherical shape is of orange"
},
{
Description: "Grapes",
Name:
"Grapes are typically an ellipsoid shape resembling a prolate spheroid."
}
]
}
]
}
]);

而buildFileTree函数是:

buildFileTree(obj: { [key: string]: any }, level: number): FileNode[] {
return Object.keys(obj).reduce<FileNode[]>((accumulator, key) => {
const value = obj[key];
const node = new FileNode();
node.filename = key;
if (value != null) {
if (typeof value === "object") {
node.children = this.buildFileTree(value, level);
} else {
node.type = value;
}
}
return accumulator.concat(node);
}, []);
}
}

上面函数的响应是:

Current Response

预期响应: Format

看来我必须对 buildFileTree 函数进行一些更改。我可以得到一些帮助吗?

当前响应的工作示例:https://stackblitz.com/edit/angular-qsb9c8-x4oaan?file=app%2Ftree-nested-overview-example.ts

最佳答案

无需将数组转换为 json,然后创建所需的必要结构。相反,通过遍历每个对象并映射所需的输出来直接使用数组 treeData,如下所示:

var treeData = [
{
Standard: "Food",
Category: [
{
Name: "Vegetable",
Tables: [
{
Description:
"The carrot ..... shape.",
Name: "Carrots"
},
{
Description:
" tomatoes come .... torpedo-shaped,",
Name: "Tomatoes"
}
]
},
{
Name: "Fruits",
Tables: [
{
Name: "Oranges",
Description: "Spherical shape is of orange"
},
{
Name: "Grapes",
Description:
"Grapes ..... spheroid."
}
]
}
]
}
];

let data = {};

for (const obj in treeData) {
const inner = {};
treeData[obj].Category.forEach(e => {
inner[e.Name] = e.Tables.map(i => i.Name)
});
data[treeData[obj].Standard] = inner;
}

console.log(data);


根据评论,如果您想在模板中对此进行迭代,请使用以下代码段:

<div *ngFor="let e1 of data | keyvalue">
{{ e1.key }}
<ul *ngFor="let e2 of e1.value | keyvalue">
<li>{{e2.key}}</li>
<ul *ngFor="let e3 of e2.value | keyvalue">
<li>{{e3.value}}</li>
</ul>
</ul>
</div>

关于javascript - 如何使用函数更改使用 JSON 的响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65166294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com