繁体   English   中英

使用 reduce 将所有子对象键放入新的对象数组中

[英]Get all the children objects key into new array of objects using reduce

目前我有一个 object,它有父子结构,这个孩子的依赖可以增加到 12-13 级,Bellow 是我有的 object curranty 的父子数组示例

{
"EMSA": {
    "North Europe Region": {
        "Denmark": {
            "a/s": {
                "VC": {
                    "VK Supplier ": {}
                },
                "DM": {
                    "DM Denmark": {}
                },
                "DQ": {
                    "DQ A/S": {}
                }
            }
        }
    },
    "East Europe Region": {
        "India": {
            "a/s India": {
                "VP": {
                    "Vp Supplier": {}
                },
                "DC": {
                    "DC india": {}
                },
                "HQ": {
                    "HQ A\S": {}
                }
            }
        }
    }
}}

我正在尝试创建一个 object 的新数组,其中包含所有键以及分配给它的新键,例如:

 { "AREA": [ "EMSA" ], "SUPER_REGION": [ "North Europe Region", "East Europe Region" ], "thirdChild": [ "Denmark", "India" ], "fourthChild": [ "a/s", "a/s India" ], "fifthchilds": [ "VK Supplier", "DM Denmark", "DQ A/S", "Vp Supplier", "DC india", "HQ A\S" ] }

到目前为止我正在尝试下面的代码,我看到 res 总是空的,我也看到只有第一层的键为 output 但无法到达子层,

下面是我的代码:

 const keyify = (obj, prefix ="") => Object.keys(obj).reduce((res, el) => { if (typeof obj[el] === "object" && obj[el].== null) { //return [..,res. ..,keyify(obj[el]. prefix + el + ";")]. } return [..,res; prefix + el], }; []); keyify(val); //here val is my object similar to 1st obj mentioned

一个简单的递归循环跟踪你在树中的深度将允许你在你的 object 中设置值。

 var myObj = { "EMSA": { "North Europe Region": { "Denmark": { "a/s": { "VC": { "VK Supplier ": {} }, "DM": { "DM Denmark": {} }, "DQ": { "DQ A/S": {} } } } }, "East Europe Region": { "India": { "a/s India": { "VP": { "Vp Supplier": {} }, "DC": { "DC india": {} }, "HQ": { "HQ A\S": {} } } } } } }; // put the names of the levels here const levelKeys = ["AREA", "SUPER_REGION", "three", "four", "five", "six"]; // recursive function that walks the tree const documentTree = (obj, acc = {}, level = 0) => { Object.entries(obj).forEach(([key, value]) => { const prop = levelKeys[level] || level; acc[prop] = acc[prop] || []; acc[prop].push(key); // loop over the child object, bump up the level documentTree(value, acc, level + 1); }); return acc; } const res = documentTree(myObj); console.log(res);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM