gpt4 book ai didi

Javascript forEach 对象数组递归

转载 作者:行者123 更新时间:2023-12-04 00:50:02 26 4
gpt4 key购买 nike


我需要一些帮助来使用对象数组循环对象

这是一个示例对象:

const node = {
documents: [{
name: "test1"
}],
children: [{
documents: [{
name: "test2"
}],
children: [{
documents: [{
name: "test3"
}],
children: []
}]
}]
};


我的问题
我尝试了这里的一些解决方案,但这并不完全是我所需要的。基本上我想将文档数组中的每个对象移动到子数组中。
我已经知道了,但目前它只是在第一个对象中执行此操作,所以不是递归的......
如果不创建弗兰肯斯坦式的代码,我就无法弄清楚......
我尝试过就像我在使用之前提到的

Array.concat()

将文档附加到子级,但仅在第一个对象中。
它应该是什么样子

const node = {
children: [
{
name: "test1"
},
{
children: [
{
name: "test2"
},
{
children: [
{name: "test3"}
]
}
]
}
]
};

现在,在每个“深度”中,文档都被“附加”给了 children 。
这应该发生在每个子键(深度)上。

有人好心帮助我吗?


编辑:

我想我的例子还不够好。这是一些实际数据:

      const node = {
id: 1,
name: "Root Node",
documents: [
{ name: "Doc Root 1", id: 1234 },
{ name: "Doc Root 2", id: 1235 }
],
children: [
{
id: 2,
name: "Sub Node Node1",
documents: [
{ name: "Doc SubNote 1 1", id: 1236 },
{ name: "Doc SubNote 1 2", id: 1237 }
],
children: [{
id: 3,
name: "Sub Sub Node Node 1",
documents: [
{ name: "Doc SubSubNote 1 1", id: 1238 },
{ name: "Doc SubSubNote 1 2", id: 1239 }
],
children: null,
addTreeNodeDisabled: true,
addLeafNodeDisabled: true,
editNodeDisabled: true,
delNodeDisabled: true,
}],
addTreeNodeDisabled: true,
addLeafNodeDisabled: true,
editNodeDisabled: true,
delNodeDisabled: true,
}
],
addTreeNodeDisabled: true,
addLeafNodeDisabled: true,
editNodeDisabled: true,
delNodeDisabled: true,
};

最佳答案

您可以通过再次调用该函数将文档副本与子文档连接起来。

var f = ({ documents, children, ...o }) => {
children = [...(documents || []), ...(children || [])].map(f);
return children.length
? { ...o, children }
: o;
},
data = { id: 1, name: "Root Node", documents: [{ name: "Doc Root 1", id: 1234 }, { name: "Doc Root 2", id: 1235 }], children: [{ id: 2, name: "Sub Node Node1", documents: [{ name: "Doc SubNote 1 1", id: 1236 }, { name: "Doc SubNote 1 2", id: 1237 }], children: [{ id: 3, name: "Sub Sub Node Node 1", documents: [{ name: "Doc SubSubNote 1 1", id: 1238 }, { name: "Doc SubSubNote 1 2", id: 1239 }], children: null, addTreeNodeDisabled: true, addLeafNodeDisabled: true, editNodeDisabled: true, delNodeDisabled: true, }], addTreeNodeDisabled: true, addLeafNodeDisabled: true, editNodeDisabled: true, delNodeDisabled: true, }], addTreeNodeDisabled: true, addLeafNodeDisabled: true, editNodeDisabled: true, delNodeDisabled: true },
result = f(data);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于Javascript forEach 对象数组递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59613256/

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