如何计算嵌套对象的深度?
我有一个嵌套对象的示例数组:
let arr = [{id: 0, children: []},
{id: 1, children:[
{id: 2, children: []},
{id: 3, children: [
{id: 4, children: []}
]}
]}
];
我需要计算每个对象的深度级别。在所有对象中我也有一个parentId 属性。
结果应该是:
let arr = [{id: 0, depth: 0, children: []},
{id: 1, depth: 0, children:[
{id: 2, depth: 1, children: []},
{id: 3, depth: 1, children: [
{id: 4, depth: 2, children: []}
]}
]}
];
我也有一个平面结构中所有对象的数组。
解决方案?
I have an expample array of nested objects:
let arr = [{id: 0, children: []},
{id: 1, children:[
{id: 2, children: []},
{id: 3, children: [
{id: 4, children: []}
]}
]}
];
I need to count depth level for each object. In all objects I have a parentId property too.
Result should be:
let arr = [{id: 0, depth: 0, children: []},
{id: 1, depth: 0, children:[
{id: 2, depth: 1, children: []},
{id: 3, depth: 1, children: [
{id: 4, depth: 2, children: []}
]}
]}
];
I have an array of all the objects in a flat structure too.
Solutions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需创建一个接受数组和深度参数的函数,该参数将该深度添加到数组中的所有对象。然后以递增的深度在
children
数组上调用它:Just make a function that takes an array and a
depth
parameter that adds that depth to all objects in an array. Then call it on thechildren
array with an incremented depth:您可以迭代数组并添加深度。
You could iterate the arrays and add a depth.
您需要编写一个对您有用的函数。
试试这个。
You need to write a function that would be count for you.
try this one.