如何将简单的JSON置于JavaScript中的JSON嵌套
我有一个返回简单JSON的API。需要根据每个节点中的“ parentId”将哪个在父/子关系中转换为嵌套的JSON数组。below是我从API中获得的示例JSON数组。.enyone可以在JavaScript中发布任何函数示例以实现这一目标吗?
我正在尝试在React中使Kendo Treelist视图。
我想要这个:
const employees = [
{
"id" :1,
"IdChild": 23890952,
"ParentId": null
},
{
"id" :2,
"IdChild": 23890953,
"ParentId": 23890952
},
{
"id":3,
"IdChild": 23890954,
"ParentId": 23890953
}
];
转换为:
const employees = [
{
"id" :1,
"IdChild": 23890952,
"ParentId": null,
"employees":[{
"id" :2,
"IdChild": 23890953,
"ParentId": 23890952,
"employees":[{
"id":3,
"IdChild": 23890954,
"ParentId": 23890953
}]
}]
},
];
出口默认员工;
I have a API which return simple json. Which need to be converted into nested JSON array in a parent/child relation based on "ParentId" in each node.Below is the sample JSON array which I get from API..Can enyone post any example of function in JavaScript to achieve this?
I'm trying to make kendo TreeList view in react.
I want this:
const employees = [
{
"id" :1,
"IdChild": 23890952,
"ParentId": null
},
{
"id" :2,
"IdChild": 23890953,
"ParentId": 23890952
},
{
"id":3,
"IdChild": 23890954,
"ParentId": 23890953
}
];
transform to this:
const employees = [
{
"id" :1,
"IdChild": 23890952,
"ParentId": null,
"employees":[{
"id" :2,
"IdChild": 23890953,
"ParentId": 23890952,
"employees":[{
"id":3,
"IdChild": 23890954,
"ParentId": 23890953
}]
}]
},
];
export default employees;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是解决方案。
说明:
我们还可以将ID作为对象的关键
Here is the solution.
Explanation:
We can also make id as a key of object
我尝试了这些解决方案,但是如果我有这样的回应,它们对我不起作用:
这就是我希望回复的样子:
I tried those solutions but they dont work for me if i have response like this:
this is how i want response to look like: