Search code examples
javascriptnonfactors-mvc-grid

Dealing with Hyphens in a JavaScript Object


I'm using an open-sourced grid library (Nonfactors-MVC-Grid) for a .NET MVC5 application and for whatever reason, the renderer converts snake_case variable names in C# to hyphens in JavaScript.

document.addEventListener('rowclick', function (e) {
    //Value in C# will be some_id
    var some_id = e.detail.data.some-id; //debugger displays this
});

Obviously, this is a terrible naming convention for JS, but I'm curious if there's an alternative way to capture this variable without having to refactor my naming conventions on the back end.


Solution

  • You can also access object property with the bracket getter ( [ ] ).
    This can be used in your case to access object property that contains hyphens.

    document.addEventListener('rowclick', function (e) {
        //Value in C# will be some_id
        var some_id = e.detail.data['some-id']; //debugger displays this
    });
    

    You could also use the same getter to get dynamic property

    document.addEventListener('rowclick', function (e) {
        //Value in C# will be some_id
        let key = 'some-id';
        var some_id = e.detail.data[key]; //debugger displays this
    });