Search code examples
datatablenestedyuiyui-datatable

YUI DataTable nested columns with JSON object with unknown keys


I am pretty new to YUI and need some help.

I have a JSON response like this:

{
    "Results":[
        {
            "alpha":57.935,
            "beta:{
                "delta":2.975,
                "omega":1.431
            },
            "gamma":{
                "theta":"0.339",
                "lambda":"1.195"
            }
        },
        {
            "alpha":87,
            "beta":{
                "lambda":2.680,
                "kappa":0.714
            },
            "gamma":{
                "zeta":"0.288",
                "epsilon":"0.289"
            }
        }
    ]
}

I would like to have a datatable with nested columns where:
1) alpha, beta and gamma are parent columns.
2) beta and gamma each have two columns formed of the JSON key-value pair (e.g., delta => 2.975).
3) The number of rows, i.e., total key-value pairs, is dynamic.

Basically, something like this:

    ----------------------------------------------
    | alpha   |      beta      |       gamma     |
    ----------------------------------------------
    | 57.935  |  delta | 2.975 |   theta | 0.339 |
    ----------------------------------------------
    |         |  omega | 1.431 |  lambda | 1.195 |
    ----------------------------------------------
    | 87.435  | lambda | 2.680 |    zeta | 0.288 |
    ----------------------------------------------
    |         |  kappa | 0.714 | epsilon | 0.289 |
    ----------------------------------------------

I have been able to generate non-nested, simple JSON responses.

My problems:
1) I have the object for each JSON child ({theta:0.339}, etc.). Both child columns will need data from this same object. How do I use it without modifying it? Should I use the same 'keyName' for both child columns in myColumnDefs?
2) How to create more than one rows where alpha td is empty?

Any help will be appreciated !


Solution

  • This is not an easy problem to solve. Barring your ability to format the JSON into individual rows before its sent to the client, you can hack together a solution using some column configurations, formatters, and a custom bodyView modelList attribute setter that flattens the data for display. http://jsbin.com/3/efigim/1/edit?javascript,live

    This would likely involve some breakage of table row -> data record associations since the bodyView's modelList contains its own Models for the rows rather than sharing a clientId. This may or may not get in your way, depending on whether you need additional features.

    But since the DataTable's data ModelList preserves the objects for beta and gamma values--only the view's representation is customized--you might be fine.

    YMMV, HTH