简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM