2

Is there any way to access a nested data when loading a lightning:datatable?

.cmp

<lightning:datatable aura:id="datatable" data="{!v.data}" columns="{!v.columns}" keyField="id"/>

.cmp controller ...

component.set("v.columns", [{
        "fieldName": "A1.B1",
        "label": "Column 1",
        "type": "text"
    },
    {
        "fieldName": "A1.B2",
        "label": "Column 2",
        "type": "text"
    }
]);
component.set("v.data", [{
    "Id": "a1J0R0000001HmIUAU",
    "A1": [{
        "B1": "Test1",
        "B2": "Test2"
    }]
}]);

How to display B1 or B2? I believe the best way is to manipulate v.data to return "A1.B1" : "Test1" and "A1.B2" : "Test2". The solution below works, but I'd like to access without having to change the JSON structure.

component.set("v.columns", [{
        "fieldName": "A1.B1",
        "label": "Column 1",
        "type": "text"
    },
    {
        "fieldName": "A1.B2",
        "label": "Column 2",
        "type": "text"
    }
]);
component.set("v.data", [{
    "Id": "a1J0R0000001HmIUAU",
    "A1.B1": "Test1",
    "A1.B2": "Test2"
}]);

I don't believe child elements are currently supported. Am I wrong?

3

This is not supported in a standard way - have a look at my regarding this:

Winter 18 <lightning:datatable> does not get values from a parent record

And the workaround is to flatten the server side result:

(Method taken from https://stackoverflow.com/questions/19098797/fastest-way-to-flatten-un-flatten-nested-json-objects)

flatten :function(data) {
    var result = {};
    function recurse (cur, prop) {
        if (Object(cur) !== cur) {
            result[prop] = cur;
        } else if (Array.isArray(cur)) {
            for(var i=0, l=cur.length; i<l; i++)
                recurse(cur[i], prop + "[" + i + "]");
            if (l == 0)
                result[prop] = [];
        } else {
            var isEmpty = true;
            for (var p in cur) {
                isEmpty = false;
                recurse(cur[p], prop ? prop+"."+p : p);
            }
            if (isEmpty && prop)
                result[prop] = {};
        }
    }
    recurse(data, "");
    return result;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.