【问题标题】:Reformating a JSON tree in node在节点中格式化 JSON 树
【发布时间】:2014-03-23 07:04:10
【问题描述】:

我正在尝试对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 进行递归,但这似乎有点矫枉过正,我很难理解它。我正在考虑一个带有回调的解决方案,但还没有完成。如有任何帮助,我将不胜感激。

【问题讨论】:

  • 那里没有任何东西看起来是异步的。你为什么要考虑Q 或回调?不能直接做同步递归吗?
  • @AaronDufour - 我想我很难理解节点中的递归。但也许我让它变得比实际更困难。

标签: javascript json node.js recursion


【解决方案1】:

递归似乎完全合理。这是一种可能的解决方案:

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);

【讨论】:

  • 我有点尴尬,就这么简单。我不知道为什么我认为它需要回调或类似 Node 的东西。谢谢。
  • 没有汗水!我也花了一些时间来了解异步风格的编程和回调(并且知道什么时候不需要)。干杯。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-11
  • 1970-01-01
  • 2014-09-27
  • 1970-01-01
  • 2012-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多