我们如何递归地重新映射 Javascript 中的嵌套数组?

How can we Recursively remap the Nested Array in Javascript?

正在寻找以递归方式重新映射 TypeScript 中的嵌套数组/Javascript。我有一个包含父对象和子对象的数组,我想用一个只有子对象和 parentId 对象键的空白数组进行克隆。例如

[{
    id: "abc",
    name: "Parent Object",
    children: [{
        id: "def",
        name: "Child 1 Object",
        parentId: "abc",
        children: [{
            id: "ghi",
            name: "Child 2 Object",
            parentId: "def",
            children: [{
                id: "jkl",
                name: "Child 3 Object",
                parentId: "ghi",

            }]
        }]
    }]
}]

上面的数组是嵌套的,它们还有其他键,但我已经提到了 id, name, parentId, children,还有 8 个键,由于复杂性,我没有在这里提到。它应该仅使用以下对象键进行克隆,其余键将在克隆数组中删除(可用键为 id、parentId、children) 它应该如下所示。

[{
    id: "abc",
    children: [{
        id: "def",
        parentId: "abc",
        children: [{
            id: "ghi",
            parentId: "def",
            children: [{
                id: "jkl",
                parentId: "ghi",

            }]
        }]
    }]
}]

您可以使用 mapfor...in 循环的递归方法来仅在值存在时分配属性。

const data = [{"id":"abc","name":"Parent Object","children":[{"id":"def","name":"Child 1 Object","parentId":"abc","children":[{"id":"ghi","name":"Child 2 Object","parentId":"def","children":[{"id":"jkl","name":"Child 3 Object","parentId":"ghi"}]}]}]}]

const f = data => 
  data.map(({ children, id, parentId }) => {
    const props = { parentId, id }, o = {}
    for (let p in props) if (props[p]) o[p] = props[p]
    if (children) o.children = f(children)
    return o
  })

console.log(f(data))