coding_hero
coding_hero

Reputation: 1769

Reformating a JSON tree in node

I'm trying a different approach to my previous question. Basically, I have a JSON object that looks like this:

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"
        }
    }
};

As you can see, there are two "top-level" items: a 'tree' object and an 'index' object. I want to parse them together to get this:

{
    "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": []
                }
            ]
        }
    ]
}

It seems like I could do recursion with Q, but it almost seems like overkill and I have a hard time getting my head wrapped around it. I'm thinking through a solution with callbacks but don't quite have it yet. I'd appreciate any help.

Upvotes: 2

Views: 137

Answers (1)

heyheyjp
heyheyjp

Reputation: 626

Recursion seems perfectly reasonable. Here's one possible solution:

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

Upvotes: 3

Related Questions