在节点中重新格式化JSON树

时间:2014-02-21 16:35:20

标签: javascript json node.js recursion

我正在尝试使用my previous question的不同方法。基本上,我有一个看起来像这样的JSON对象:

var data = {
    "tree": {
        "id": "99842",
        "label": "Bill",
        "children": [
            {
                "id": "27878",
                "label": "Tom",
                "children": []
            }
        ]
    },
    "index": {
        "27878": {
            "birthdate": "1/21/1988",
            "spouse": "June",
            "hometown": "Tulsa, OK"
        },
        "99842": {
            "birthdate": "4/15/1969",
            "spouse": "Mary",
            "hometown": "Dallas, TX"
        }
    }
};

如您所见,有两个“顶级”项:“树”对象和“索引”对象。我想将它们解析在一起得到这个:

{
    "rows": [
        {
            "id": "99842",
            "data": [
                {
                    "birthdate": "4/15/1969",
                    "spouse": "Mary",
                    "hometown": "Dallas, TX"
                }
            ],
            "rows": [
                {
                    "id": "27878",
                    "data": [
                        {
                            "birthdate": "1/21/1988",
                            "spouse": "June",
                            "hometown": "Tulsa, OK"
                        }
                    ],
                    "rows": []
                }
            ]
        }
    ]
}

好像我可以用Q做递归,但它几乎看起来有点矫枉过正,我很难把头缠在它上面。我正在考虑使用回调的解决方案,但还没有完成它。我很感激任何帮助。

1 个答案:

答案 0 :(得分:3)

递归似乎非常合理。这是一个可能的解决方案:

function nestObjects(tree, index) {

    var output;

    if (tree && index) {

        output = {
            id: tree.id,
            data: index[tree.id],
            rows: []
        };

        if (Array.isArray(tree.children) && tree.children.length) {

            for (var i = 0, len = tree.children.length; i < len; i++) {

                output.rows.push(nestObjects(tree.children[i], index));
            }
        }
    }

    return output;
}

var result = {
    rows: [nestObjects(data.tree, data.index)]
};

console.log(result);
相关问题