javascript – 递归地从“对象数组”中选择一个字段

我正在寻找一种方法,使用JavaScript / Lodash来检索与输入对象数组相同的例外,但是只想保留选定的字段.

我也可以将这个问题表述为对仅保留某些字段的对象数组进行深度复制.

例如,给定以下数组:

[
    {
        "id": "q1",
        "text": "Q1 text",
        "children": [
            {
                "id": "q11",
                "text": "t",
                "children": [
                    {
                        "id": "q111",
                        "text": "t"
                    },
                    {
                        "id": "q112",
                        "text": "t"
                    }
                ]
            }
        ]
    },
    {
        "id": "q2",
        "text": "e",
        "children": [
            {
                "id": "q22",
                "text": "e"
            }
        ]
    },
    {
        "id": "q3",
        "text": "e"
    }
]

输出应如下.这与上面的对象数组完全相同,但只保留id和children的id.孩子们可以深入任何层次.

[
        {
            "id": "q1",
            "children": [
                {
                    "id": "q11",
                    "children": [
                        {
                            "id": "q111",
                        },
                        {
                            "id": "q112"
                        }
                    ]
                }
            ]
        },
        {
            "id": "q2",
            "children": [
                {
                    "id": "q22",
                }
            ]
        },
        {
            "id": "q3"
        }
]

解决方法:

您可以创建一个带有数组的函数,并将其映射到只包含id和子对象的对象.要设置id,只需复制id,设置返回对象上的子节点,将children数组以递归方式传递回函数:

let arr = [{"id": "q1","text": "Q1 text","children": [{"id": "q11","text": "t","children": [{"id": "q111","text": "t"},{"id": "q112","text": "t"}]}]},{"id": "q2","text": "e","children": [{"id": "q22","text": "e"}]},{"id": "q3","text": "e"}]

const justIDs = (arr) => arr.map(({id, children}) => {
        let ret = {id}
        if(children) ret.children = justIDs(children)
        return ret
    })

let filtered = justIDs(arr)
console.log(filtered)
上一篇:javascript – Lodash _.hasIntersection?


下一篇:javascript – lodash.js在function.apply上的部分应用程序